/* server.c */
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <strings.h> #define PORT 8088 int main() { char buf[1024]; int sockfd; int len; int ret; struct sockaddr_in inet_addr; struct sockaddr_in addr_clnt; sockfd=socket(AF_INET, SOCK_DGRAM, 0); if(sockfd==-1) { perror("创建SOCK失败!"); return(-1); }
inet_addr.sin_family=AF_INET; inet_addr.sin_port=htons(PORT); inet_addr.sin_addr.s_addr=htonl(INADDR_ANY); bzero((void *)&(inet_addr.sin_zero), 8); len=sizeof(inet_addr);
ret=bind(sockfd, (struct sockaddr *)&inet_addr, len); if(ret==-1) { perror("帮定IP失败!"); close(sockfd); return(-1); }
printf("\nsockfd:%d", sockfd); while(1) { fprintf(stdout, "\nWait recv, sockfd=%d....", sockfd); fflush(stdout); ret=recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&addr_clnt, &len); if(ret<0) { perror("接收失败!"); break; } buf[ret]=0; printf("\nFrom:[%s], [%s]", inet_ntoa(addr_clnt.sin_addr), buf); if(!(strncmp(buf, "stop", 4))) break; } close(sockfd); return(0); }
|