9
Sockets…
“In Unix, everything is a file.”
And this is true also for networks. Of course you won’t learn socket programing just with this example, but it shows how to create a socket, connect, send and recieve data, and close it, is that simple.
I’ll be making a nice tutorial on network programing lather, for now, the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define MAXSIZE 255
void usage(char *pname){
fprintf(stderr,"Uso:%s <IP>\n",pname);
exit(1);
}
int main(int argc, char *argv[]){
if(argc!=2)
usage(argv[0]);
int sockfd;
int n;
struct sockaddr_in end;
char buff[MAXSIZE];
char sBuff[MAXSIZE];
memset(buff,’\0′,sizeof(char)*MAXSIZE);
memset(sBuff,’\0′,sizeof(char)*MAXSIZE);
strcpy(sBuff,”GET /\n”);
/* Creating the socket */
if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0 ){
perror(”socket”);
return errno;
}
/* Creating the structure */
end.sin_family=AF_INET;
end.sin_port=htons(80);
if( inet_pton(AF_INET,argv[1],&end.sin_addr) < 0){
perror(”inet_pton”);
return errno;
}
memset(end.sin_zero,’\0′,8);
/* Connecting */
if(connect(sockfd,(struct sockaddr*)&end,sizeof(struct sockaddr)) < 0){
perror(”connect”);
return errno;
}
/* Sending a request…should return an error, or the return from the HTML command stored in sBuff */
if( (send(sockfd, sBuff, strlen(sBuff), 0)) < 0){
perror(”send”);
close(sockfd);
return errno;
}
/* Getting the HTML return */
while( (n=read(sockfd,buff,MAXSIZE)) > 0){
fprintf(stdout,”%s”,buff);
}
/* closing */
close(sockfd);
return 0;
}
Zarnick