· 6 years ago · Feb 23, 2019, 06:14 PM
1/*
2** talker.c -- a datagram "client" demo
3** taken from beej
4*/
5
6#include <stdio.h>
7#include <stdlib.h>
8#include <unistd.h>
9#include <errno.h>
10#include <string.h>
11#include <sys/types.h>
12#include <sys/socket.h>
13#include <netinet/in.h>
14#include <arpa/inet.h>
15#include <netdb.h>
16#include "common.h"
17
18
19#define SERVERPORT "4950" // the port users will be connecting to
20#define SERVER_IP_ADDRESS "192.168.1.12"
21
22int main()
23{
24 int sockfd, sent_recv_bytes = 0;
25 struct addrinfo hints, *servinfo, *p;
26 int rv;
27 int numbytes;
28 test_struct_t client_data;
29 result_struct_t result;
30
31
32 memset(&hints, 0, sizeof hints);
33 hints.ai_family = AF_UNSPEC;
34 hints.ai_socktype = SOCK_DGRAM;
35
36 if ((rv = getaddrinfo(SERVER_IP_ADDRESS, SERVERPORT, &hints, &servinfo)) != 0) {
37 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
38 return 1;
39 }
40
41 // loop through all the results and make a socket
42 for(p = servinfo; p != NULL; p = p->ai_next) {
43 if ((sockfd = socket(p->ai_family, p->ai_socktype,
44 p->ai_protocol)) == -1) {
45 perror("talker: socket");
46 continue;
47 }
48
49 break;
50 }
51
52 if (p == NULL) {
53 fprintf(stderr, "talker: failed to create socket\n");
54 return 2;
55 }
56
57 int addr_len = sizeof(struct sockaddr);
58
59 while(1) {
60
61 /*Prompt the user to enter data*/
62 /*You will want to change the promt for the second task*/
63 printf("Enter name : ?\n");
64 scanf("%s", &client_data.name);
65 printf("Enter age : ?\n");
66 scanf("%s", &client_data.age);
67 printf("Enter group : ?\n");
68 scanf("%s", &client_data.group);
69
70 if ((numbytes = sendto(sockfd, &client_data, sizeof(test_struct_t), 0, p->ai_addr, p->ai_addrlen)) == -1){
71 perror("talker: sendto");
72 exit(1);
73 }
74
75 printf("talker: sent %d bytes to %s\n", numbytes, SERVER_IP_ADDRESS);
76
77 }
78
79}