1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/types.h> 4 #include <
ID: 3555540 • Letter: 1
Question
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <arpa/inet.h>
7 #include <unistd.h>
8
9 int main(int argc, char **argv)
10 {
11 int clnt_fd;
12 struct sockaddr_in serv_addr;
13 char c;
14
15 clnt_fd = socket(AF_INET, SOCK_STREAM, 0);
16 serv_addr.sin_family = AF_INET;
17 serv_addr.sin_port = htons(atoi(argv[2]));
18 serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
19 connect(clnt_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
20 while ((c = (char) getchar()) != EOF) {
21 write(clnt_fd, &c, 1);
22 read(clnt_fd, &c, 1);
23 putchar((int) c);
24 }
25
26 close(clnt_fd);
27 }
Explanation / Answer
17 serv_addr.sin_port = htons(atoi(argv[2])); //takes 3rd string of command line input
18 serv_addr.sin_addr.s_addr = inet_addr(argv[1]); //takes 2nd string of command line input
These lines require command line arguments as inputs(if you don't give any then segmentation fault).
after compilation execute by:
./a.out any-ip.address any-port
for eg: ./a.out 10.121.224.117 80
Here ./a.out is the executable generated after compilation(it may be different depending on the platform, generally "a" for windows and ./a.out for linux.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.