赞
踩
udp:无连接(也就是说只要创建好了套接字绑定了地址信息之后就可以发消息了)
服务器:
1、创建套接字
2、绑定地址信息
3、接收消息 recvfrom
4、关闭套接字
客户端:
1、创建套接字
2、发消息 sendto
3、关闭套接字
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);
- //udpserver.c
- #include <stdio.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
-
-
- int main(int argc, char *argv[])
- {
- if(argc < 2)
- {
- printf("please input port\n");
- return -1;
- }
- int sockFd = -1;
- struct sockaddr_in servAddr = {0};
- struct sockaddr_in cliAddr = {0};
- socklen_t len = sizeof(cliAddr);
- int ret;
- char buf[100] = {0};
-
- //创建套接字
- sockFd = socket(AF_INET, SOCK_DGRAM, 0);
- if(sockFd < 0)
- {
- perror("socket error!");
- return -1;
- }
- printf("socket ok!\n");
- //绑定服务器的地址信息
- servAddr.sin_family = PF_INET;
- servAddr.sin_port = htons(atoi(argv[1]));
- servAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
- ret = bind(sockFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
- if(ret < 0)
- {
- perror("bind error!");
- close(sockFd);
- return -1;
- }
- printf("bind ok!\n");
- //从客户端接收消息
- ret = recvfrom(sockFd, buf, sizeof(buf), 0, (struct sockaddr *)&cliAddr, &len);
- if(ret < 0)
- {
- perror("recvfrom
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。