#include #include #include #include #include #include #include #include #include #include #include #include #include #define BUFFER_SIZE 200 typedef struct { int port; char *host[15]; } info; void *checkPort(void *sarg) { info *pinfo = (info *)sarg; int port = pinfo->port; char *host = *pinfo->host; int clientSocket; struct sockaddr_in serverAddr; char sendbuf[BUFFER_SIZE]; char recvbuf[BUFFER_SIZE]; int iDataNum; if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return NULL; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr(host); printf("=================================\n"); if (connect(clientSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { perror("connect"); return NULL; } printf("Connect to: %s:%d...success\n", host, port); sprintf(sendbuf, "send port_%d", port); send(clientSocket, sendbuf, strlen(sendbuf), 0); printf("Send msg_%d: %s\n", port, sendbuf); recvbuf[0] = '\0'; iDataNum = recv(clientSocket, recvbuf, BUFFER_SIZE, 0); recvbuf[iDataNum] = '\0'; printf("Read ack msg_%d: %s\n", port, recvbuf); printf("=================================\n"); close(clientSocket); return NULL; } void *checkUPort(void *sarg) { info *pinfo = (info *)sarg; int port = pinfo->port; char *host = *pinfo->host; int clientSocket; struct sockaddr_in serverAddr; char sendbuf[BUFFER_SIZE]; char recvbuf[BUFFER_SIZE]; int iDataNum; if ((clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror("socket"); return NULL; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr(host); printf("=================================\n"); // if (connect(clientSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { // perror("connect"); // return NULL; // } // printf("Connect to: %s:%d...success\n", host, port); sprintf(sendbuf, "send msg port_%d by udp", port); socklen_t sin_size = sizeof(*(struct sockaddr*)&serverAddr); sendto(clientSocket, sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&serverAddr, (int)sin_size); printf("Send msg_%d by udp: %s\n", port, sendbuf); recvbuf[0] = '\0'; iDataNum = recvfrom(clientSocket, recvbuf, BUFFER_SIZE, 0, (struct sockaddr *)&serverAddr, &sin_size); recvbuf[iDataNum] = '\0'; printf("Read ack msg_%d from udp: %s\n", port, recvbuf); printf("=================================\n"); close(clientSocket); return NULL; } int main() { int port = 6020; char *host = "127.0.0.1"; info *infos = malloc(10 * sizeof(info)); info *uinfos = malloc(10 * sizeof(info)); for (size_t i = 0; i < 10; i++) { port++; printf("For test: %s:%d\n", host, port); info *pinfo = infos++; *pinfo->host = host; pinfo->port = port; checkPort(pinfo); info *uinfo = uinfos++; *uinfo->host = host; uinfo->port = port; checkUPort(uinfo); } }