dev/cpp/multithreading/udp_socket.c

63 lines
1.3 KiB
C

#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
volatile int is = 1;
void sig_int(int sig_no)
{
is = 0;
return;
}
int main()
{ int sock, len;
struct sockaddr_in addr;
char buff[256];
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
fprintf(stderr, "%d ", errno);
perror("socket()");
return 1;
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(10000);
signal(SIGINT, sig_int);
if (bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) == -1)
{
fprintf(stderr, "%d ", errno);
perror("bind()");
}
while(is)
{ memset(buff, 0, 256);
len = sizeof(struct sockaddr_in);
memset(&addr, 0, sizeof(struct sockaddr_in));
if (recvfrom(sock, buff, 255, 0, (struct sockaddr*)&addr, &len) == -1)
{
fprintf(stderr, "%d ", errno);
perror("recvfrom()");
}
addr.sin_addr.s_addr = htonl(addr.sin_addr.s_addr);
addr.sin_port = htons(addr.sin_port);
printf("%d.%d.%d.%d:%d (%d) > %s\n", (addr.sin_addr.s_addr >> 24),
((addr.sin_addr.s_addr >> 16) & 0xff),
((addr.sin_addr.s_addr >> 8) & 0xff),
(addr.sin_addr.s_addr & 0xff), addr.sin_port, len, buff);
}
close(sock);
return 0;
}