最近一直在做linux的网络,现在作个总结,陆续贴出来。
在网上搜了很多资料 ,其中周立发的博客对我的学习参考作用最大,谢谢前辈。
直接上代码吧,一个很简单udp通信的例子,分别为服务器端和客户端的代码。
#include <sys/types.h> #include <sys/socket.h> #include<pthread.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc != 2) { printf("Usage: %s port\n", argv[0]); exit(1); } printf("Welcome! This is a UDP server, I can only received message from client and reply with same message\n"); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(atoi(argv[1])); addr.sin_addr.s_addr = htonl(INADDR_ANY); int sock; if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(1); } char buff[512]; struct sockaddr_in clientAddr; int n; int len = sizeof(clientAddr); while (1) { n = recvfrom(sock, buff, 511, 0, (struct sockaddr*)&clientAddr, &len); if (n>0) { buff[n] = 0; printf("%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff); n = sendto(sock, buff, n, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr)); if (n < 0) { perror("sendto"); break; } } else { perror("recv"); break; } } return 0; }编译这个文件:gcc udp_server.c -o server
运行服务端:./server 5500 .(这个端口自己可以随意)
#include <sys/types.h> #include <sys/socket.h> #include<pthread.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char **argv) { char buff[512] = "---------> The message is from clinet! <----------"; if (argc != 3) { printf("Usage: %s server-ip port", argv[0]); exit(1); } printf("This is a UDP client\n"); struct sockaddr_in addr; int sock; if ( (sock=socket(AF_INET, SOCK_DGRAM, 0)) <0) { perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_port = htons(atoi(argv[2])); addr.sin_addr.s_addr = inet_addr(argv[1]); if (addr.sin_addr.s_addr == INADDR_NONE) { printf("Incorrect ip address!"); close(sock); exit(1); } int len = sizeof(addr); while (1) { // gets(buff); int n; if( sendto(sock, buff, strlen(buff), 0, (struct sockaddr *)&addr, sizeof(addr)) < 0){ perror("sendto"); close(sock); break; }else{ printf("clinet send success!\n"); } n = recvfrom(sock, buff, 512, 0, (struct sockaddr *)&addr, &len); if (n>0) { buff[n] = 0; printf("received %d bytes:",n); puts(buff); } else if (n==0) { printf("server closed\n"); close(sock); break; } else if (n == -1) { perror("recvfrom"); close(sock); break; } } return 0; }
编译这个文件:gcc udp_clinet.c -o server
运行服务端:./clinet 192.168.1.121 5500
linux网络编程源代码:http://download.csdn.net/detail/yanyuanfen2011/6595113