/* ============================================================================ Name : UDPclient.c Author : vestinfo Version : 1.1 Copyright : www.cnblogs.com/vestinfo Description : A simple UDP client, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #define REMOTEPORT 8888 #define REMOTEIP "127.0.0.1" #define CLIENT_PORT 9999 #define CLIENT_IP "192.168.77.172" #define MAXLENGTH 256 int main(int argc,char *argv[]) { int sockfd; char msg[MAXLENGTH]; struct sockaddr_in servaddr; struct sockaddr_in clientaddr; socklen_t addr_len; addr_len = sizeof(servaddr); /* 创建数据报套接字 */ if(( sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) { perror("error"); exit(1); } /* 绑定client的地址和端口,也可不绑定由内核指定 */ bzero(&clientaddr, sizeof(clientaddr)); clientaddr.sin_family = AF_INET; clientaddr.sin_port = htons(CLIENT_PORT); clientaddr.sin_addr.s_addr = inet_addr(CLIENT_IP); if(bind(sockfd, (struct sockaddr *)&clientaddr, sizeof(clientaddr)) < 0) { perror("error"); exit(1); } /* server的地址结构 */ bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(REMOTEPORT); servaddr.sin_addr.s_addr = inet_addr(REMOTEIP); while(1) { bzero(msg, MAXLENGTH); printf("please input msg\n"); read(STDIN_FILENO, msg, MAXLENGTH); //从键盘(终端)键入msg sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&servaddr, addr_len); //发送msg给目的套接字addr recvfrom(sockfd, msg, MAXLENGTH, 0, (struct sockaddr *)&servaddr, &addr_len); //接受目的套接字传来的msg printf("Received message from server:%s\n",msg); } }