This repository was archived by the owner on Nov 29, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathsrv.c
More file actions
55 lines (48 loc) · 1.72 KB
/
srv.c
File metadata and controls
55 lines (48 loc) · 1.72 KB
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
54
55
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSZ 200
int port = 6180; /* no significance */
int main(int argc, char *argv[]) {
char buf[BUFSZ];
int rc;
/**********************************************************
* create an IPv4/UDP socket, not yet bound to any address
*********************************************************/
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
printf("socket: %s\n", strerror(errno));
exit(-1);
}
/**********************************************************
* internet socket address structure: our address and port
*********************************************************/
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(port);
/**********************************************************
* bind socket to address and port we'd like to receive on
*********************************************************/
if (bind(fd, (struct sockaddr*)&sin, sizeof(sin)) == -1) {
printf("bind: %s\n", strerror(errno));
exit(-1);
}
/**********************************************************
* uses recvfrom to get data along with client address/port
*********************************************************/
do {
struct sockaddr_in cin;
socklen_t cin_sz = sizeof(cin);
rc = recvfrom(fd,buf,BUFSZ,0,(struct sockaddr*)&cin,&cin_sz);
if (rc==-1) printf("recvfrom: %s\n", strerror(errno));
else {
printf("received %d bytes from %s:%d: %.*s\n", rc,
inet_ntoa(cin.sin_addr), (int)ntohs(cin.sin_port), rc, buf);
}
} while (rc >= 0);
}