fixes for Power64
[tridge/junkcode.git] / connectfrom.c
1 /*
2   force TCP connections to come from a specific IP
3
4   compile with:
5      gcc -o connectfrom.so -fPIC -shared -o connectfrom.so connectfrom.c -ldl
6 */
7
8 #include <stdio.h>
9 #include <pwd.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <dlfcn.h>
13 #include <stdlib.h>
14 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <arpa/inet.h>
17
18 int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen)
19 {
20         static int (*real_connect)(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);
21         const char *address = getenv("CONNECTFROM");
22         
23         if (!real_connect) {
24                 real_connect = dlsym((void*)-1, "connect");
25         }
26
27         if (address) {
28                 struct sockaddr_in myaddr;
29                 socklen_t myaddrlen = sizeof(myaddr);
30                 myaddr = *(struct sockaddr_in *)serv_addr;
31                 inet_aton(address, &myaddr.sin_addr);
32                 myaddr.sin_port = 0;
33                 
34                 bind(sockfd, (struct sockaddr *)&myaddr, myaddrlen);
35         }
36
37         return real_connect(sockfd, serv_addr, addrlen);
38 }