erver.sin_port = htons(PORT); /* Remember htons() from "Conversions" section? =) */
server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY puts your IP address automatically */
bzero(&(server.sin_zero),8); /* zero the rest of the structure */
if(bind(fd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ /* calls bind() */
printf("bind() error\n");
exit(-1);
}
if(listen(fd,BACKLOG) == -1){ /* calls listen() */
printf("listen() error\n");
exit(-1);
}
while(1){
sin_size=sizeof(struct sockaddr_in);
if ((fd2 = accept(fd,(struct sockaddr *)&client,&sin_size))==-1){ /* calls accept() */
printf("accept() error\n");
exit(-1);
}
printf("You got a connection from %s\n",inet_ntoa(client.sin_addr) ); /* prints client's IP */
send(fd2,"Welcome to my server.\n",22,0); /* send to the client welcome message */
close(fd2); /* close fd2 */
}
}
/* <---- SOURCE CODE ENDS HERE ----> */
9. A STREAM CLIENT EXAMPLE
=======================================
/* <---- SOURCE CODE STARTS HERE ----> */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> /* netbd.h is needed for struct hostent =) */
#define PORT 3550 /* Open Port on Remote Host */
#define MAXDATASIZE 100 /* Max number of bytes of data */
int main(int argc, char *argv[])
{
int fd, numbytes; /* files descriptors */
char buf[MAXDATASIZE]; /* buf will store received text */
struct hostent *he; /* structure that will get information about remote host */
struct sockaddr_in server; /* server's address information */
if (argc !=2) { /* this is used because our program will need one argument (IP) */
printf("Usage: %s <IP Address>\n",argv[0]);
exit(-1);
}
if ((he=gethostbyname(argv[1]))==NULL){ /* calls gethostbyname() */
printf("gethostbyname() error\n");
exit(-1);
}
if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){ /* calls socket() */
printf("socket() error\n");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(PORT); /* htons() is needed again */
server.sin_addr = *((struct in_addr *)he->h_addr); /*he->h_addr passes "*he"'s info to "h_addr" */
bzero(&(server.sin_zero),8);
if(connect(fd, (struct sockaddr *)&server,sizeof(struct sockaddr))==-1){ /* calls connect() */
printf("connect() error\n");
exit(-1);
}
if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1){ /* calls recv() */
printf("recv() error\n");
exit(-1);
}
buf[numbytes]='\0';
printf("Server Message: %s\n",buf); /* it prints server's welcome message =) */
close(fd); /* close fd =) */
}
/* <---- SOURCE CODE ENDS HERE ----> */