-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.bound_host1.c
60 lines (44 loc) · 1.11 KB
/
16.bound_host1.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
//
// Created by satellite on 5/4/2023.
//
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "arpa/inet.h"
#include "sys/socket.h"
#define BUF_SIZE 30
void error_handling(char* message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
int main(int argc , char *argv[])
{
int sock;
char message[BUF_SIZE];
struct sockaddr_in my_adr , your_adr;
socklen_t adr_sz;
int str_len , i;
if (argc != 2) {
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
sock = socket(PF_INET,SOCK_DGRAM,0);
memset(&my_adr,0,sizeof(my_adr));
my_adr.sin_family = AF_INET;
my_adr.sin_port = htons(atoi(argv[1]));
my_adr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock,(struct sockaddr*)&my_adr,sizeof(my_adr)) == -1)
error_handling("bind() error");
for(int i=0;i<3;i++)
{
sleep(5);
adr_sz = sizeof(your_adr);
str_len = recvfrom(sock,message,BUF_SIZE,0,(struct sockaddr*)&your_adr,&adr_sz);
printf("Message %d : %s \n",i+1,message);
}
close(sock);
return 0;
}