[国嵌攻略][092][UDP网络程序设计]
server.c
#include <sys/socket.h> #include <netinet/in.h> #include <strings.h> #include <stdio.h> #define SERVER_PORT 3333 void main(){ //创建标识 int serverfd; serverfd = socket(AF_INET, SOCK_DGRAM, 0); //建立UDP连接 //绑定地址 struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; //设置协议 serverAddr.sin_port = htons(SERVER_PORT); //设置端口 serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); //设置地址 bzero(serverAddr.sin_zero, 8); //设置为零 bind(serverfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)); //接收数据 char buffer[2048]; struct sockaddr_in clientAddr; socklen_t clientAddrLen; clientAddrLen = sizeof(struct sockaddr); recvfrom(serverfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddr, &clientAddrLen); //显示数据 char *clientIPAddr; clientIPAddr = (char *)inet_ntoa(clientAddr.sin_addr.s_addr); printf("server recvice from %s:\n%s", clientIPAddr, buffer); //关闭连接 close(serverfd); }
client.c
#include <sys/socket.h> #include <netinet/in.h> #include <strings.h> #include <stdio.h> #define SERVER_PORT 3333 int main(int argc, char **argv){ //参数检查 if(argc != 2){ printf("Usage:\n\t%s <ip address>\n", argv[0]); return -1; } //创建标识 int clientfd; clientfd = socket(AF_INET, SOCK_DGRAM, 0); //建立UDP连接 //输入数据 char buffer[2048]; printf("client send to %s:\n", argv[1]); fgets(buffer, sizeof(buffer), stdin); //发送数据 struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; //设置协议 serverAddr.sin_port = htons(SERVER_PORT); //设置端口 serverAddr.sin_addr.s_addr = inet_addr(argv[1]); //设置地址 bzero(serverAddr.sin_zero, 8); //设置为零 sendto(clientfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)); //关闭连接 close(clientfd); return 0; }