51 lines
1.3 KiB
C
51 lines
1.3 KiB
C
|
#include <arpa/inet.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
void run_client(int port, char *msg) {
|
||
|
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||
|
if (sockfd < 0) {
|
||
|
fprintf(stderr, "socket: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
struct sockaddr_in server_addr;
|
||
|
memset(&server_addr, 0, sizeof(server_addr));
|
||
|
server_addr.sin_family = AF_INET;
|
||
|
server_addr.sin_addr.s_addr = INADDR_ANY;
|
||
|
server_addr.sin_port = htons(port);
|
||
|
if (connect(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr))) {
|
||
|
fprintf(stderr, "connect: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
int rv = sendto(sockfd, msg, strlen(msg), 0, (const struct sockaddr *)&server_addr, sizeof(server_addr));
|
||
|
if (rv < 0) {
|
||
|
fprintf(stderr, "sendto: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
char buffer[100];
|
||
|
memset(&buffer, 0, sizeof(buffer));
|
||
|
socklen_t server_addr_len = sizeof(server_addr);
|
||
|
rv = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&server_addr, &server_addr_len);
|
||
|
if (rv < 0) {
|
||
|
fprintf(stderr, "recvfrom: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
printf("Server reply: %s\n", buffer);
|
||
|
|
||
|
close(sockfd);
|
||
|
}
|
||
|
|
||
|
int main(int arc, char *argv[]) {
|
||
|
|
||
|
run_client(2137, argv[1]);
|
||
|
|
||
|
return 0;
|
||
|
}
|