/* * Parse [host]/port[/ttl]. Return 0 if ok, -1 if error; set sockaddr and * ttl value. */ #include #include #include #include #include #include "sysdep.h" #define DEBUG #include #include #include #ifdef DEBUG #include #endif int OpenSock(u_int32_t addr, u_short port, unsigned char* ttl); void getLocal(struct sockaddr_in *p, int ssock); void nonblock(int fd); extern struct in_addr host2ip(char *); extern void ip2host(char * addr); int hpt(char *h, struct sockaddr *sa, unsigned char *ttl) { char *s; struct sockaddr_in *sin = (struct sockaddr_in *)sa; #ifdef DEBUG printf("host after call hpt %s\n", h); #endif sin->sin_family = AF_INET; /* first */ s = strchr(h, '/'); if (!s) { return -1; } else { int port; /* replace joy.ece.cmu.edu/1234 / with /0, h would end with * joy.ece.cmu.edu/0 == joy.ece.cmu.edu */ *s = '\0'; port = atoi(s+1); sin->sin_port = htons(port); if (port & 1) { return -2; } s = strchr(s+1, '/'); if (s && ttl) { *ttl = atoi(s+1); } #ifdef DEBUG printf("host before call host2ip in hpt is %s\n", h); #endif sin->sin_addr = host2ip(h); #ifdef DEBUG printf("host after call host2ip in hpt is %s\n", h); printf("address after host2ip is %u\n",ntohl(sin->sin_addr.s_addr)); #endif } return 0; } /* hpt */ void getLocal(struct sockaddr_in *p, int ssock) { int len = sizeof(*p); memset((char *)p, 0, sizeof(*p)); p->sin_family = AF_INET; /* * returns the current name for ssock_ and put in sockaddr* p */ if (getsockname(ssock, (struct sockaddr *)p, &len) < 0) { perror("getsockname"); p->sin_addr.s_addr = 0; p->sin_port = 0; } #ifdef DEBUG ip2host((char*) &(p->sin_addr.s_addr)); printf(" Binding from Local Port is %d \n",ntohs(p->sin_port)); #endif } void nonblock(int fd) { int flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK|O_NDELAY; if (fcntl(fd, F_SETFL, flags) == -1) { perror("fcntl: F_SETFL"); exit(1); } } int OpenSock(u_int32_t addr, u_short port, unsigned char* ttl) { int fd; struct sockaddr_in sin; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); exit(1); } memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = port; sin.sin_addr.s_addr = INADDR_ANY; if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("bind"); exit(1); } sin.sin_addr.s_addr = addr; if(connect(fd, (struct sockaddr *)&sin, sizeof(sin))>0){ perror("connet"); exit(1); } return (fd); }