..:: MacHacking.net ::.. Article from MacHacking.net Knowledge Base: http://kb.machacking.net ********** Title: Socket Programming in C Author: digitalViper Author Contact: digitalViper@hotmail.com ********** -(C)Copyright 2003 -www.udirp.tk (If you use this on your site, please do not edit anything, including this information at the top.) *************************************************************************** SOCKET PROGRAMMING IN C Disclaimer: Some of the source codez provided in this tutorial should be used for research and learning process only and not to be used for malicious purposes.I am not responsible for anything... Introduction: In this tutorial I will introduce you guys how to use socket programming routines in your C code .The tutorial assumes that you know well C programming and also that you are familiar with the operating system Linux or Unix or FreeBSD... If you are not familiar with the above operating systems then no problem you can still go forward...I will also discuss the code for WinDoze . What is a SOCKET ? A socket is a structure mainted by a BSD-Unix system to handle network connections... In man pages a socket is something like an end point of communication.. If i say i created a socket between two computers I mean that i created communication between two computers..So a socket is nothing but a communication when we say socket programming we mean network programming or internet programming...Socket programming is very necessary if you want to be a good hacker ...Since a a hacker knows how to break into a computer remotely (the legal way ;)...So if you dont know about it you are a good lamer but not a hacker... What about all the Network tools ? Yeah I know alot of hacking tools out there ... And i've used some of them when i was a hacking enthusiast but not now ... What if you need a tool which must work according to your commands... Now here you need to code one for yourself because some of the lame proggies will not work... Some theory about Protocols: TCP [Transmission Control Protcol]: This is based on a Three Hand Way Shake process..Like if you want connect to a target computer first you will send a syn packet if the target is alive and accepts the packet it will return you a ack packet and after receiving a ack packet from the target again your system will sent a syn packet confirming the connection : Host Target syn ----------------------------> syn (reached) ack (reached) <--------------------------- ack syn ----------------------------> syn (reached) <-----------Connection Established-------------> Also in tcp transmission the data is guaranteed to reach the target... UDP [USER DATAGRAM PROTOCOL]: Thiz protocol will send a packet to the target computer by writing all the information on its headers like the target computer's IP address etc.. when it moves from the destination its not guaranteed that it will reach the target computer since there is not communication made ,thats why its called connection less protcol...Also the data which is arrived from the host computer using udp protocl may be not in order I mean for example if you sent a,b,c it is not confirm that they will reach like a,b,c but may be b,a,c or in any other disordered position..If you still want to study these protcols there is alot of theory about it on RFC 768...But its enough if you want to move in this tutorial... What about compiler ? The compiler I'll be using to create source codez for you is gcc however you can use cc or anyother compiler as well > I am talking about Linux ..If you want to code for windows I recommend you working in the Visual C environment ..Get Microsoft Visual C 6.0 ... Structures that we will be using in our code: This structure is used for holding the socket address: struct sockaddr{ unsigned short sa_family; char sa_data[14]; }; sa_family is what i said like AF_INET (for address family) OR PF_INET (for protocol family) ,,sa_data is used for holding the port number and address of the socket... struct sockaddr_in server: #include "netinet/in.h" struct sockaddr_in{ short in sin_family; unsigned short int sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; The above struct will be used to access the socket address... sin_family is the same as i discussed above.. sin_port will be the destination port address ,,the struct in_addr will be used by us to store the internet address or IP address unsigned char sin_zero[8] to zero the rest of the struct... struct in_addr{ unsigned long s_addr; }; Again i say the above struct in_addr is used to store the ip address... For Example if you want to store the ip in the above address we will do something like this: struct in_addr addr; addr.sin_addr.s_addr=inet_addr("127.0.0.1"); Note: inet_addr() call stores ip address in string format. So how can we create a socket ?? A socket is created by a simple function : int socket(int domain,int type,int protocol); You have to include the header files i.e "sys/types.h" and "sys/socket.h" PS its returns -1 on error.. domain: It specifies whether you want to use Address family or Protocol family ..It basically is means of communication ..We will use address family that is : AF_INET AF means Address Family INET means internet.. type: type simply means like which protcol you want to use..Commonly used protocols are SOCK_STREAM for TCP and SOCK_UDP for UDP or SOCK_RAW for raw sockets.. protocol: Not to care much about it .. you can use either IPPROTO_IP for SOCK_STREAM or IPPROTO_UDP for UDP but we will put here 0 since we dont need the above shit... How can we declare a socket call in our code: int socket_fd; /*an integer which we will be using to store the socket file descriptor/* if((socket_fd=socket(AF_INET,SOCK_SREAM,0))==-1){ printf("socket() error..."); exit(1); } The above code simply creates a TCP communication ,,If an error has occured it will return a -1 and so the second line of code will be executed ... When i was learning socket programming in C i was very much terrified at first time when i saw the codez and shit but gradually i became familiar with the code so if you think you are not going well my advise is Read On!! Read the tutorial to the last and practise the codez which I will be providing later in this tutorial ... The bind() call: How would a server know that a client's socket is calling it ? This will allow other sockets to find it. This call is used mostly on server side when you want to recieve connections.. This call is basically used for naming the socket ..which is used later in broadcasting... int bind(int sockfd,struct sockaddr *addr,socklen_t addrlen); int sockfd is the file descriptor of the socket() call , so the *addr is a pointer to the struct sockaddr which we used in our bind call and then we have socklen_t addrlen which is nothing but an integer returning the size of teh struct ..We can get the size by the call sizeof(struct sockaddr) So using the bind call in our code will look like: int socket_fd; struct sockaddr_in addr; if((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1){ //THE SOCKET PROCEDURE printf("Socket Error...\n"); exit(1); } addr.sin_addr.s_addr=INADDR_ANY; //stores the local machine's IP Address addr.sin_port=htons(1000); //stores the IP address addr.sin_family=AF_INET; //AF_INET memset(&(addr.sin_zero),'\0',8); /* memset will be used to zero the remaining structure */ if(bind(socket_fd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1){ printf("Bind Error...\n"); exit(1); } ALERT: THE ABOVE CODEZ ARE JUST AN IDEA WE ARE NOT INTO ACTUAL CODEZ ..WE WILL DEAL WITH THAT LATER.. SO JUST UNDERSTAND WHAT IS HAPPENING IN THE ABOVE SMALL SNIPPETS connect ?: So you've decided to connect to the server.. A connect call looks like this: int connect(int socket_fd,struct sockaddr* server,int addresslen); socket_fd is what you know or if you dont know it go up ^ know it and then come and if you still dont know shut down your computer take some rest and then come and if still then better shoot yourself ;) socket_fd is the socket file descriptor, server is the pointer to the struct sockaddr and addresslen is sizeof(struct sockaddr) or sizeof(server)... Hey listen: Looks like: int listen(int socket_fd,int backlog); socket_fd ? no,no I am not going to explain it.. its the socket file descriptor again you know.. backlog is the number of connections that your server wants to accept...You can simply put it 4 or 2 or 6 or whatever you want... accept: It is used whenever your server's door is knocked by a client and you want to accept the connection.. int accept(int socket_fd,struct sockaddr *add,int *addrlen); int *addrlen is a pointer containing the address of the struct sockaddr_in,,, Now its time to code... Which Platform Which compiler ?: If you are on Blindows oh sorry i mean windows then you should use Visual C++ 6.0 compiler and on Linux we have cc and gcc both will work on Sun Solaris cc is ok...:) On Visual C++ be sure to add WSock32.lib from Project->Settings->Links. Now We'll be coding a simple client/server proggie ,client which sends a message to the server.. -------------------tcp client------------------------------------- #include "stdio.h" #include "winsock.h" #define PORT 1200 void main(int argc,char *argv[]){ WSADATA wsda; WSAStartup(0x0101,&wsda); struct sockaddr_in server; int sockfd; struct hostent *h; char *message="Hello Server"; if(argc!=2){ printf("Usage : client "); exit(1); } if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ printf("Socket Error..."); exit(1); } if((h=gethostbyname(argv[1]))==NULL){ fprintf(stderr,"Host Name Error..."); exit(1); } server.sin_addr=*((struct in_addr*)h->h_addr); server.sin_port=htons(PORT); server.sin_family=AF_INET; if(connect(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ fprintf(stderr,"Connection out..."); exit(1); } send(sockfd,message,strlen(message),0); WSACleanup(); closesocket(sockfd); } ----------------------Code Ends--------------------------------- Above is the code for tcp client I have coded by above client in VC 6. If you want to code it for linux add all the of the below headers files: #include #include #include #include #include #include #include #include #include Though some of the above header files are useless but you should include them as my linux PC is down so i can't compile the codes. Now i will explain each of the block in pieces: #include "stdio.h" #include "winsock.h" #define PORT 1200 void main(int argc,char *argv[]){ WSADATA wsda; WSAStartup(0x0101,&wsda); struct sockaddr_in server; int sockfd; struct hostent *h; char *message="Hello Server"; First of all we include the header files then we define PORT to be 1200 then the main function the next to lines are for Windows we initialize the winsock version etc. struct sockaddr_in server is used to store information about the server as i mentioned above.int sockfd is used to hold the socket file descriptor struct hostent *h is new struct to you guys so i'll explain it in a little deep,the following is its main structure: struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; }; *h_name is the name of the host, char **h_aliases for alternate host names,,int h_addrtype this would be AF_INET, int h_length is the length of the address and char **h_addr_list is the address list.. if(argc!=2){ printf("Usage : client "); exit(1); } if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ printf("Socket Error..."); exit(1); } if((h=gethostbyname(argv[1]))==NULL){ fprintf(stderr,"Host Name Error..."); exit(1); } server.sin_addr=*((struct in_addr*)h->h_addr); server.sin_port=htons(PORT); server.sin_family=AF_INET; NOw the above piece of code is simple ,the first block checks for arguments,,The second initializes the socket routine,,the third block is simple as well may be new to you..We use it here to resolve the Host name ..the next three lines will fill the struct sockaddr_in with the information needed to store about server.,, if(connect(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ fprintf(stderr,"Connection out..."); exit(1); } send(sockfd,message,strlen(message),0); WSACleanup(); closesocket(sockfd); } the connect() function will try to connect to the server if its successful then send() will be the next function to be executed which sends the message to the server... Now time for TCP server ------------------------tcp server------------------ #include "stdio.h" #include "winsock.h" #define PORT 1200 #define BACKLOG 4 int main(){ WSADATA wsda; WSAStartup(0x0101,&wsda); struct sockaddr_in server; struct sockaddr_in client; int sockfd,sockfd2,n_bytes; char msg[50]; if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ printf("Socket error..."); return 0; } server.sin_addr.s_addr=INADDR_ANY; /*INADDR_ANY will simply put your IP */ server.sin_port=htons(PORT); /*htons means host to network short server.sin_family=AF_INET; if(bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ printf("Cannot bind..."); return 0; } if(listen(sockfd,BACKLOG)){ /*Listening printf("Error Listening..."); return 0; } while (1){ int size=sizeof(struct sockaddr_in); if((sockfd2=accept(sockfd,(struct sockaddr*)&client,&size))==-1){ printf("Accept Error..."); return 0; } if((n_bytes=recv(sockfd2,command,50,0))==-1){ printf("Error Recv..."); return 0; } msg[n_bytes]='\0'; printf("Client's Message:%s",msg); } WSACleanup(); closesocket(sockfd); /*used to close the socket */ closesocket(sockfd2); return 0; } --------------------------Code Ends------------------------- The above code well be easier for you ,if you have understood the tcp client code..Because the server does nothing but listens on port 1200.And after accepting the connection and recieving the data from the client it is displayed... Here comes the end of the tutorial.Now I recommend you to check out the codez section there are alot of good source code on socket programming which will be helpful for you ... The End -For comments,suggestions,critisism write to : -digitalViper@hotmail.com ********** Article from MacHacking.net Knowledge Base: http://kb.machacking.net