1 /* 2 * Network related functions 3 */ 4 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <linux/in.h> 8 #include <unistd.h> 9 #include <netinet/in.h> 10 #include <arpa/inet.h> 11 #include <netdb.h> 12 #ifdef DEBUG 13 #include <stdio.h> 14 #endif 15 #include "net.h" 16 17 18 /* 19 * Create a listening port on tcp port PORT 20 */ 21 int createlisten(int port) 22 { 23 struct sockaddr_in localname; 24 int sockFd; 25 sockFd=socket(AF_INET,SOCK_STREAM,IPPROTO_IP); 26 localname.sin_family=AF_INET; 27 localname.sin_port=htons(port); 28 localname.sin_addr.s_addr=INADDR_ANY; 29 if (bind(sockFd,(struct sockaddr *) & localname,sizeof(localname))==-1) { perror("bind");return(-1); } 30 if (listen(sockFd,1024)==-1) { perror("listen"); return(-1); } 31 return(sockFd); 32 } 33 34 35 /* 36 * Close that socket, yeah. 37 */ 38 void closeconnection(int sockfd) { 39 shutdown(sockfd, 1); 40 close(sockfd); 41 } 42 43 int createconnection_tcp(char *host, int port) { 44 int sockid; 45 struct hostent *hostinfo; 46 struct sockaddr_in sock; 47 if ((hostinfo=gethostbyname(host))==NULL) { 48 if (!inet_aton(host,&sock.sin_addr)) 49 return(-1); 50 } else { 51 memcpy(&sock.sin_addr.s_addr,hostinfo->h_addr_list[0],hostinfo->h_length); 52 } 53 sock.sin_family=AF_INET; 54 sock.sin_port=htons(port); 55 if ((sockid=socket(AF_INET, SOCK_STREAM, 0))<0) 56 return(-1); 57 connect(sockid, (struct sockaddr *) &sock, sizeof(sock)); 58 return(sockid); 59 } |