cmd_client.c
1 #include <stdio.h> 2 #include <sys/socket.h> 3 #include <netinet/in.h> 4 #include <arpa/inet.h> 5 #include <string.h> 6 #include <unistd.h> 7 #include <stdlib.h> 8 #include <sys/types.h> 9 #include <pthread.h> 10 #include <errno.h> 11 12 #define SOCKET_PORT_CMD_CLIENT 2001 13 #define SOCKET_PORT_CMD_SERVER 2002 14 #define LOCAL_ADDRESS ("127.0.0.1") 15 #define RECV_BUFFER_LEN 512 16 int main(int argc, char *argv[]) 17 { 18 int opt = 0; 19 int socketFd = -1; 20 struct sockaddr_in stAddr; 21 struct sockaddr_in stClientAddr; 22 struct timeval stTimeInterval = {0,10000}; 23 24 int recvlen = 0; 25 int addrlen = 0; 26 struct sockaddr_in stRemoteAddr = {0}; 27 char szBuffer[RECV_BUFFER_LEN] = {0}; 28 char szSendBuffer[RECV_BUFFER_LEN] = {0}; 29 int index = 5; 30 if (0 > (socketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) 31 { 32 printf("create socket error, errno(%d)\n",errno); 33 return -1; 34 } 35 memset(&stAddr, 0, sizeof(stAddr)); 36 stAddr.sin_family = AF_INET; 37 stAddr.sin_port = htons(SOCKET_PORT_CMD_CLIENT); 38 stAddr.sin_addr.s_addr = inet_addr(LOCAL_ADDRESS); 39 40 if(0 > bind(socketFd, (struct sockaddr*)&stAddr, sizeof(struct sockaddr))) 41 { 42 printf("bind error, errno(%d)\n",errno); 43 return -1; 44 } 45 if(0 != setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, &stTimeInterval, sizeof(struct timeval))) 46 { 47 printf("setsockopt error, errno(%d)\n",errno); 48 return -1; 49 } 50 51 memset(&stRemoteAddr, 0, sizeof(stRemoteAddr)); 52 stRemoteAddr.sin_family = AF_INET; 53 stRemoteAddr.sin_port = htons(SOCKET_PORT_CMD_SERVER); 54 stRemoteAddr.sin_addr.s_addr = inet_addr(LOCAL_ADDRESS); 55 56 for (int i = 1; i < argc; i++) 57 { 58 if (i == 1) 59 { 60 strcat(szSendBuffer, argv[i]); 61 } 62 else 63 { 64 strcat(szSendBuffer, " "); 65 strcat(szSendBuffer, argv[i]); 66 } 67 } 68 printf("send buffer:%s\n", szSendBuffer); 69 if(-1 ==sendto(socketFd,szSendBuffer,strlen(szSendBuffer),0,(struct sockaddr*)&stRemoteAddr,sizeof(stRemoteAddr))) 70 { 71 perror("sendto error"); 72 close(socketFd); 73 exit(1); 74 } 75 76 while(1) 77 { 78 if(0 < (recvlen = recvfrom(socketFd,szBuffer,RECV_BUFFER_LEN,0,(struct sockaddr*)&stRemoteAddr,&addrlen))) 79 { 80 printf("recv msg:%s\n", szBuffer); 81 close(socketFd); 82 exit(1); 83 } 84 sleep(5); 85 if (0 >= index--) 86 { 87 break; 88 } 89 } 90 91 printf("recv error\n"); 92 return 0; 93 }View Code
标签:socketFd,struct,stAddr,int,stRemoteAddr,cmd,include,客户端 From: https://www.cnblogs.com/tianxincode/p/18418907