-
-
Save infiniteregrets/19305d2c6e258a25ddc91792cc5e558a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) | |
{ | |
int sockfd; | |
struct sockaddr_in serv_addr, cli_addr; | |
struct iovec iov[1]; | |
struct msghdr message; | |
struct msghdr message1; | |
char buffer[1024]; | |
int bytes_received; | |
socklen_t cli_len; | |
sockfd = socket(AF_INET, SOCK_DGRAM, 0); | |
if (sockfd < 0) { | |
perror("Error creating socket"); | |
return 1; | |
} | |
// memset(&serv_addr, 0, sizeof(serv_addr)); | |
// serv_addr.sin_family = AF_INET; | |
// serv_addr.sin_port = htons(8090); | |
// serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
// if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { | |
// perror("Error binding socket to address"); | |
// return 1; | |
// } | |
for (;;) { | |
cli_len = sizeof(cli_addr); | |
memset(&cli_addr, 0, sizeof(cli_addr)); | |
cli_addr.sin_family = AF_INET; | |
cli_addr.sin_port = htons(8060); | |
cli_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
iov[0].iov_base = buffer; | |
iov[0].iov_len = sizeof(buffer); | |
message.msg_name = &cli_addr; | |
message.msg_namelen = cli_len; | |
message.msg_iov = iov; | |
message.msg_iovlen = 1; | |
message.msg_control = NULL; | |
message.msg_controllen = 0; | |
bytes_received = recvmsg(sockfd, &message, 0); | |
// print the address from which the message was received | |
printf("Received message from addr: %s, port: %d", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port)); | |
if (bytes_received < 0) { | |
perror("Error receiving message"); | |
return 1; | |
} | |
printf("Received %d bytes from %s: %.*s\n", bytes_received, | |
inet_ntoa(cli_addr.sin_addr), bytes_received, buffer); | |
if (sendmsg(sockfd, &message, 0) < 0) { | |
perror("Error sending response"); | |
return 1; | |
} | |
} | |
close(sockfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment