below im trying to create a function makeaddr that will take a few options and take most of the work out of creating a socket, the code compiles ok with no warnings, but it seg faults.
I'm pretty sure it has something to do with the int sock and me passing the socket file descriptor ?
in the socket and bind functions calls i originally didnt have the *s = only had s = but it compiled with warnings and segfaulted.
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/wait.h> #include <errno.h> void bail (char *msg){ fputs(strerror(errno),stderr); fputs(": ",stderr); fputs(msg,stderr); fputc('\n',stderr); exit(1); } int makeaddr(void * addr, int len, int *s, char *type, char *ip, int port){ //takes &addr,sizeof(addr), &sock,"TCP",ipaddr, port number int Default_port = 3099; struct sockaddr_in *ad = (struct sockaddr_in *)addr; memset(&addr,0,len); ad->sin_family = AF_INET; if(strcmp(ip,NULL)==0){ ad->sin_addr.s_addr = INADDR_ANY; } else{ ad->sin_addr.s_addr = inet_addr(ip); } if(port == 0){ ad->sin_port = htons(Default_port); } else{ ad->sin_port = htons(port); } //we have created the address structure. Now create the socket if(strcmp(type,"TCP")==0){ if(*s = socket(AF_INET,SOCK_STREAM,0)== -1) bail("TCP Sock Error"); if(bind(*s,(struct sockaddr*)&addr,len)== -1){ bail("TCP Bind Error"); } printf("TCP Socket Successfully created: On Port %d \n",(int)ad->sin_port); } else{ if(*s = socket(AF_INET,SOCK_DGRAM,0)== -1) bail("UDP Sock Error"); if(bind(*s,(struct sockaddr*)&addr,len)== -1){ bail("UDP Bind Error"); } printf("UDP Socket Successfully created: On Port %d \n",(int)ad->sin_port); } } int main(int argc, char *argv[]){ int sock; struct sockaddr_in addr; //takes &addr,sizeof(addr), &sock,"TCP",ipaddr, port number makeaddr(&addr,sizeof(addr),&sock,"TCP",NULL,0); close(sock); return 0; }



LinkBack URL
About LinkBacks



