Networks III: Homework
You must print this sheet out and write/type
answers on it!
-
In the client code given below, identify the types of the
following expressions
p->h_addr_list[0]
*ip
&mysa
mysa.sin_addr.s_addr
(struct sockaddr*)&mysa
-
Identify the point in the client code below at which the
socket is bound to a port number.
-
What sepcifies the hostname for the server we'll be
connecting to?
-
What specifies the port number for the server we'll be
connecting to?
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char **argv)
{
// Print usage
if (argc == 1) { fprintf(stderr,"usage: %s <hostname>!\n",argv[0]); exit(1); }
// Set up socket
int sfd = socket(AF_INET,SOCK_STREAM,0);
if (sfd == -1) { fprintf(stderr,"Socket not created!\n"); exit(2); }
// Get IP address from symbolic name
struct hostent *p;
p = gethostbyname(argv[1]);
if (p == NULL) { fprintf(stderr,"Name not found!\n"); exit(1); }
unsigned int *ip = (unsigned int*)(p->h_addr_list[0]);
// Set up address structure
struct sockaddr_in mysa;
mysa.sin_family = AF_INET;
mysa.sin_addr.s_addr = *ip;
mysa.sin_port = htons(10000);
// Connect!
if (connect(sfd,(struct sockaddr*)&mysa,sizeof(mysa)) != 0)
{
fprintf(stderr,"Client could not connect!\n");
exit(3);
}
// Communicate with server
char inc, outc;
while(scanf("%c",&inc) == 1)
{
write(sfd,&inc,1);
read(sfd,&outc,1);
printf("%c",outc);
}
close(sfd);
return 0;
}