-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21.c
54 lines (43 loc) · 1.48 KB
/
21.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define Fail(msg)\
do {perror(msg); return 1; } while(0)
int main() {
//Allocate socket, datagram
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
Fail("Failed to create socket");
struct sockaddr_in local_addr = {
.sin_family = AF_INET,
.sin_port = htons(7542),
.sin_addr.s_addr = htonl(INADDR_ANY)
};
struct sockaddr_in remote_addr;
socklen_t remote_addr_size = sizeof(remote_addr);
char remote_addr_str[INET_ADDRSTRLEN];
socklen_t local_addr_size= sizeof(local_addr);
if (bind(sock, (const struct sockaddr *)&local_addr, sizeof(local_addr)))
Fail("Failed to bind");
char buf[1]="H";
if ((sendto(sock, buf, 1,MSG_NOSIGNAL,(struct sockaddr*)&local_addr, local_addr_size))<0)
Fail("Failed in send to");
char data[2048];
ssize_t data_len = recvfrom(sock, data, sizeof(data), 0, (const struct sockaddr *)&remote_addr, &remote_addr_size);
if (data_len < 0) {
perror("Failed to receive");
return 0;
}
if (strcmp(inet_ntop(remote_addr.sin_family, &remote_addr.sin_addr, remote_addr_str, sizeof(remote_addr_str)),"NULL")==0)
Fail("Failed while inet_ntop");
printf("received packet from %s:%d, content: '%.*s'\n", remote_addr_str, ntohs(remote_addr.sin_port), (int) data_len, data);
close(sock);
return 0;
}