Link to home
Start Free TrialLog in
Avatar of yac678
yac678

asked on

multiple source IPs

I have a web server acting as as a client to a 3rd party. I would like to perform two requests to the 3rd party from the server, and each request should appear to the 3rd party as if coming from a different IP. The server runs on Linux and already has two IPs. The 3rd party has has only one port for receiving incoming requests. The server code is written in Java so writing a Java application for this purpose is doable.
Is there a way to achieve this?
Avatar of for_yan
for_yan
Flag of United States of America image

Avatar of yac678
yac678

ASKER

It is basically the same question, just slightly rephrased. Since I got no solution I entered a moderation process. Still got no attention from experts and was told then (probably by an automatic message) to delete the question and resubmit it. I think a question "restart" may help me get a solution.
Avatar of Mick Barry

You can probably send through two different proxies, but this has nothing to do with your server having
two ip addreses - unless you can set up these addresses as two different proxies
> You can probably send through two different proxies, but this has nothing to do with your server having
> two ip addreses - unless you can set up these addresses as two different proxies

Thats what I already posted, please do not repeat previous posts

It was by no means stated there anything like that - please read attentively what you posted
>> The server runs on Linux and already has two IPs.

Just create two Sockets and bind them to each IP and then make a request from each. The incoming request can parameterize which ip address is to be used
Avatar of yac678

ASKER

Setting up proxy servers seems complicated to me because I assume the hosting company would need to do that for me. Unless there was a way to set up my own proxy server on the same box.
Creating sockets and binding them to the different IPs seems to me like the direction I prefer. Is there a code sample you can recommend for doing this in Java? I am asking on purpose because a previous attempt at doing this has failed - not sure why - so I am restarting.
> Creating sockets and binding them to the different IPs seems to me like the direction I prefer.

doubt that will help you
I think you should rather seek  help from network specialists
>>objects: doubt that will help you

Why not? If this server has multiple interfaces on the same subnet, then binding to an interface is the only way to control which IP gets bound on the client side of a connect call, unless you have 2 different routes and 2 different remote addresses to connect to. The OP says his 2 connections must go to one remote address, so the kernel will route it or you will route it in the connect using bind.

To OP: Using a proxy server is one solution, if you bind each proxy to a different one of the IP addresses. If you don't have a proxy, and plan to use someone elses proxy, then the connection will appear to have come from the proxy, not your own IP addresses.

If the requirement is that the connection must come from your two original IP addresses, then setting up a local proxy will be essentially the same as binding to a specific IP with a socket connect call. The advantage with the proxy is you'll have to write less code.

Given a Linux server with multiple IPs, the OS still has to decide which IP address to bind to for an outgoing connection. An outgoing client connection will go through the default route, unless you otherwise bind to a specific interface as noted by CEHJ. A proxy server will, by default, itself be bound to 0.0.0.0, unless the proxy config has supports binding.

>>@for_yan: I think you should rather seek  help from network specialists

@for_yan,

I think this is the asker's intent when posting on Expert's Exchange in the first place. He posted in 2 networking zones.

So if this is your only suggestion, please refrain from posting in (cluttering) the question. The asker has already complained about receiving no help on a previous question, and of your responses in this thread, you pointed out possible duplicate, repeated another expert's advice, and noted that he should seek help from specialists.
Avatar of yac678

ASKER

I just tried the code below. The output I am getting is:
Binding to IP 195.28.181.7:1024
Connecting to host www.whatismyip.com
File: /automation/n09230945.asp
Client socket created successfully
java.net.SocketException: Already bound
        at java.net.Socket.bind(Unknown Source)
        at control.util.IPBoundURLReader2.read(IPBoundURLReader2.java:56)
        at control.util.IPBoundURLReader2.test(IPBoundURLReader2.java:189)
        at control.util.IPBoundURLReader2.main(IPBoundURLReader2.java:218)
Source:
null

----------------------
I tried various ports - same response. Here is the code:

package control.util;
import java.io.*;
import java.net.*;

public class IPBoundURLReader2 {
    private static IPBoundURLReader2 instance;
    private static final String IP_TO_BIND_TO = "195.28.181.7";

    public static IPBoundURLReader2 getInstance() throws IOException {
        if (instance == null) {
            instance = new IPBoundURLReader2();
        }
        return instance;
    }

public static void main(String[] args) {
        try {
            IPBoundURLReader2.getInstance().test();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    public void test() throws IOException {
        String url = "http://www.whatismyip.com/automation/n09230945.asp";
        String source = read(url, IP_TO_BIND_TO);
        System.out.println("Source:\n"+source);
    }

    public String read(String urlString, String ipToBindTo) throws IOException {
        Socket clientSocket = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlString);
            String host = url.getHost();
            final int localPort = 1024;
            System.out.println("Binding to IP " + ipToBindTo + ":" + localPort);
            String file = url.getFile();
            if (file == null || file.equals("")) {
                file = "index.html";
            }

            System.out.println("Connecting to host " + host);
            System.out.println("File: "+file);
            byte[] bytes = getIPBytes(ipToBindTo);
            InetAddress localAddr = InetAddress.getByAddress(bytes);
            InetAddress remoteAddr = InetAddress.getByName(host);

            clientSocket = new Socket(remoteAddr, 80);
            System.out.println("Client socket created successfully");
            clientSocket.bind(new InetSocketAddress(localAddr, localPort));
            System.out.println("Client socket bound successfully");
            System.out.println("Socket created");
            br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            System.out.println("Writing to output stream");
            OutputStream outputStream = clientSocket.getOutputStream();
            String request = "GET " + file + " HTTP/1.0\r\n" +
                    "Host: " + host + "\r\n" +
          "\r\n";
            write(outputStream, request);
            outputStream.flush();
            System.out.println("Reading response");
            return readResponse(br);
        }catch(Exception e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
        return null;
    }

    private byte[] getIPBytes(String ipToBindTo) {
        byte[] bytes = new byte[4];
        String[] sBytes = ipToBindTo.split("\\.");
        bytes[0] = Integer.valueOf(sBytes[0]).byteValue();
        bytes[1] = Integer.valueOf(sBytes[1]).byteValue();
        bytes[2] = Integer.valueOf(sBytes[2]).byteValue();
        bytes[3] = Integer.valueOf(sBytes[3]).byteValue();
        return bytes;
    }

    private void write(OutputStream out, String line1) throws IOException {
        System.out.print(line1);
        out.write(line1.getBytes());
    }
    public static String readResponse(BufferedReader in){
        StringBuffer buffer = new StringBuffer();
        String s = null;
        try {
            while ((s = in.readLine()) != null) {
                buffer.append(s + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                in.close();
            } catch (Exception e) { /* ignore */
            }
        }
        return buffer.toString();
    }
 
}
Avatar of yac678

ASKER

As to the proxy suggestion - can anyone recommend a good link for setting up a local proxy on the Linux box?
The line:
>> clientSocket = new Socket(remoteAddr, 80);

Creates, binds and connects all in the constructor, so you can't rebind it. Instead, you need to create and bind it in separate calls.

clientSocket = new Socket();
//... assign addresses and ports
clientSocket.bind
clientSocket.connect
If you want to use a proxies on your own network, you'll have to configure two boxes, each with their own externally-facing, routeable address - possibly easier to use proxies external to the network.

With the current multi-homed box, take care when you bind to the two IPs that they're also externally-facing, routeable addresses - if NAT is being used, you might find the other end sees only one IP address instead of two different ones. So check with whatismyip.com - as you seem to be trying to do
The source IP is picked up based on the destination IP's routing information with the O/S. If both the IPs from the source is route-able to destination use output policy of iptables to allow an IP and deny the other one and vise-verse.


Cheers..
Avatar of yac678

ASKER

I changed the socket creation code to the following:

clientSocket = new Socket();
System.out.println("Client socket created successfully");
clientSocket.bind(new InetSocketAddress(localAddr, localPort));
System.out.println("Client socket bound successfully");
clientSocket.connect(new InetSocketAddress(remoteAddr, 80));
System.out.println("Socket created");

The output is:
className=control.util.IPBoundURLReader2
Binding to IP 195.28.181.7:1024
Connecting to host www.whatismyip.com
File: /automation/n09230945.asp
Client socket created successfully
Client socket bound successfully
... program pauses for about 2 minutes on the connect call...
java.net.ConnectException: Connection timed out
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(Unknown Source)
        at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at control.util.IPBoundURLReader2.read(IPBoundURLReader2.java:59)
        at control.util.IPBoundURLReader2.test(IPBoundURLReader2.java:191)
        at control.util.IPBoundURLReader2.main(IPBoundURLReader2.java:220)
Source:
null

This is very much were I got stuck in the previous discussion. Only there I used the single line constructor Socket(remoteAddr, remotePort, localAddress, localPort).
Any idea what is going on? Is the client waiting for the server? Why does the program get stuck after the connect call?
Please show what you're doing in the code. You need to set the header below btw for whatismyip to work correctly
Connection: Keep-Alive

Open in new window

See the following for 'issues' with whatismyip : http:Q_26945078.html

For what you want to do, it would probably be easier and less error-prone to use a Socket factory and then use URLConnection in the normal way

Avatar of yac678

ASKER

>> Please show what you're doing in the code
The entire code is posted in this thread. See the class IPBoundURLReader2 aove in message 35714275 and modification in message 35719197.
>> You need to set the header below btw for whatismyip to work correctly
I added the line
clientSocket.setKeepAlive(true);
still, the same result as before.
>> See the following for 'issues' with whatismyip
This is one of my earlier issues (see author). Fortunately, this one is solved.
Any other ideas why the program gets stuck after the connect call?
>>his is one of my earlier issues (see author). Fortunately, this one is solved.

LOL - i didn't notice it was you in the earlier question.


Obviously it's *not* solved if you're still finding it stuck. Make sure you're using the exact code i showed you earlier
Avatar of yac678

ASKER

Yes, the previous issue IS solved. It talks about an invalid hostname problem and there is no local IP binding done there. That problem was solved again - if you follow the issue carefully. Please note that if I take away the local IP binding code from the code above I get a response from whatismyip.com without any problem.
Again, binding the socket to a local IP and port causes the program to get stuck on the connect call. I am still looking for an answer.
>> Please note that if I take away the local IP binding code from the code above I get a response from whatismyip.com without any problem.


OK, that's different. Can you post the full code you're using please? Also try using the code with some other target address to see if it still gets stuck
Avatar of yac678

ASKER

The full code I am using is below. I tried other URLs - same problem.


package control.util;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class IPBoundURLReader2 {
    private static IPBoundURLReader2 instance;
    private static final String IP_TO_BIND_TO = "195.28.181.7";
    private static int MIN_PORT_NUMBER = 1024;
    private static int MAX_PORT_NUMBER = 65535;

    private IPBoundURLReader2() throws IOException {
    }
    public static IPBoundURLReader2 getInstance() throws IOException {
        if (instance == null) {
            instance = new IPBoundURLReader2();
        }
        return instance;
    }

    public String read(String urlString, String ipToBindTo) throws IOException {
        Socket clientSocket = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlString);
            String host = url.getHost();
            final int localPort = /*65534*/1024;
            System.out.println("Binding to IP " + ipToBindTo + ":" + localPort);
            String file = url.getFile();
            if (file == null || file.equals("")) {
                file = "index.html";
            }

            System.out.println("Connecting to host " + host);
            System.out.println("File: "+file);
            byte[] bytes = getIPBytes(ipToBindTo);
            InetAddress localAddr = InetAddress.getByAddress(bytes);
            InetAddress remoteAddr = InetAddress.getByName(host);

//            clientSocket = new Socket(remoteAddr, 80);
            clientSocket = new Socket();
            System.out.println("Client socket created successfully");
            clientSocket.bind(new InetSocketAddress(localAddr, localPort));
            System.out.println("Client socket bound successfully");
            clientSocket.setKeepAlive(true);
            clientSocket.connect(new InetSocketAddress(remoteAddr, 80));
            System.out.println("Socket created");
            br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            System.out.println("Writing to output stream");
            OutputStream outputStream = clientSocket.getOutputStream();
            String request = "GET " + file + " HTTP/1.0\r\n" +
                    "Host: " + host + "\r\n" +
          "\r\n";
            write(outputStream, request);
            outputStream.flush();
            System.out.println("Reading response");
            return readResponse(br);
        }catch(Exception e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
        return null;
    }

    private byte[] getIPBytes(String ipToBindTo) {
        byte[] bytes = new byte[4];
        String[] sBytes = ipToBindTo.split("\\.");
        bytes[0] = Integer.valueOf(sBytes[0]).byteValue();
        bytes[1] = Integer.valueOf(sBytes[1]).byteValue();
        bytes[2] = Integer.valueOf(sBytes[2]).byteValue();
        bytes[3] = Integer.valueOf(sBytes[3]).byteValue();
        return bytes;
    }

    private void write(OutputStream out, String line1) throws IOException {
        System.out.print(line1);
        out.write(line1.getBytes());
    }
    public static String readResponse(BufferedReader in){
        StringBuffer buffer = new StringBuffer();
        String s = null;
        try {
            while ((s = in.readLine()) != null) {
                buffer.append(s + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                in.close();
            } catch (Exception e) { /* ignore */
            }
        }
        return buffer.toString();
    }
    public void test() throws IOException {
        String url = "http://www.whatismyip.com/automation/n09230945.asp";
//        String url = "http://www.yahoo.com";
//        String url = "http://siteexplorer.search.yahoo.com/search?p=yahoo.com&bwm=i&bwmf=u&bwms=p&fr=yfp-t-701&fr2=seo-rd-se";
        String source = read(url, IP_TO_BIND_TO);
        System.out.println("Source:\n"+source);
    }

    public static void main(String[] args) {
        try {
            IPBoundURLReader2.getInstance().test();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
Have you been able to prove the viability of using these separate addresses outside Java?
Considering 1.1.1.1 and 1.1.1.2 are two source IPs available and route-able to 3.3.3.3. If you intend 3.3.3.3 to receive packets once from 1.1.1.1 and then 1.1.1.2 simply change the routing information on o/s using the command route add and route del. Example if you have route 1.1.1.1 to destination 3.3.3.3 all packets to 3.3.3.3 will appear to come from 1.1.1.1 later delete this route and add 1.1.1.2 to destination 3.3.3.3 all the packets will appear to come from 1.1.1.2. The routing commands on linux are as follows.

source 1.1.1.1
route add -net 3.3.3.3 netmask 255.255.255.255 gw 1.1.1.1 eth0
route del -net 3.3.3.3 netmask 255.255.255.255 gw 1.1.1.2 eth0

source 1.1.1.2
route add -net 3.3.3.3 netmask 255.255.255.255 gw 1.1.1.2 eth0
route del -net 3.3.3.3 netmask 255.255.255.255 gw 1.1.1.1 eth0
Avatar of yac678

ASKER

>> have you been able to prove the viability of using these separate addresses outside Java?
Yes. I was able to access the web server using both IPs.

>> source 1.1.1.2
>> route add -net 3.3.3.3 netmask 255.255.255.255 gw 1.1.1.2 eth0
The output of ifconfig and route is below. Shouldn't the line be
route add -net <destination IP> netmask 255.255.255.255 gw * eth0:1
?
ifconfig:
eth0      Link encap:Ethernet  HWaddr 00:50:56:A5:1C:6A
          inet addr:195.28.181.130  Bcast:195.28.181.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:fea5:1c6a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:133418074 errors:0 dropped:0 overruns:0 frame:0
          TX packets:775860 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:584091028 (557.0 MiB)  TX bytes:156581542 (149.3 MiB)

eth0:1    Link encap:Ethernet  HWaddr 00:50:56:A5:1C:6A
          inet addr:195.28.181.7  Bcast:195.28.181.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1


route:

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
195.28.181.0    *               255.255.255.0   U     0      0        0 eth0
169.254.0.0     *               255.255.0.0     U     0      0        0 eth0
default         ptco-omcC-195.2 0.0.0.0         UG    0      0        0 eth0
route del -net 195.28.181.0 netmask 255.255.255.0 gw * eth0

When you want your source ip to be 195.28.181.130
route del -net <destination IP> netmask 255.255.255.255 gw * eth0:1
route add -net <destination IP> netmask 255.255.255.255 gw 195.28.181.130 eth0

When you want your source ip to be 195.28.181.7
route del -net <destination IP> netmask 255.255.255.255 gw * eth0
route add -net <destination IP> netmask 255.255.255.255 gw 195.28.181.7 eth0:1


Cheers.

Avatar of yac678

ASKER

Why do I need to perform
route del -net 195.28.181.0 netmask 255.255.255.0 gw * eth0
?
It is a pre-configuration done by the hosting company.
It would probably worthwhile simply printing your current routing table with route
Avatar of yac678

ASKER

I already did! See previous message (35785604) at the end of the message.
No - that was at the end of having REconfigured the network
Avatar of yac678

ASKER

I'm affraid I lost you. Do you mean that you would like to see the output of "route" after the network is reconfigured?
Why do I need to perform
route del -net 195.28.181.0 netmask 255.255.255.0 gw * eth0?

if you don't delete the above route it means all destination hosts from 195.28.181.1 to 195.28.181.254 are routable

when you add the entry below after deleting the above route.
route add -net <destination IP> netmask 255.255.255.255 gw 195.28.181.130 eth0
this will mean the destination IP can be reached only from 195.28.181.130.

Cheers.
Avatar of yac678

ASKER

>> if you don't delete the above route it means all destination hosts from 195.28.181.1 to 195.28.181.254 are routable

I assume you mean that all above hosts will see 195.28.181.130 as the source IP.

>> if you don't delete the above route it means all destination hosts from 195.28.181.1 to 195.28.181.254 are routable

but if the destination host is not in the range 195.28.181.1 to 195.28.181.254 - can I leave the above route?
Maybe all traffic from 195.28.181.130 has to go through a router in the range 195.28.181.1 to 195.28.181.254? Is there a way to find out?
>>Do you mean that you would like to see the output of "route" after the network is reconfigured?

No i meant BEFORE any reconfiguration is done. If your attempts to use both IPs outside Java worked, i don't see why you need to reconfigure any routes
Avatar of yac678

ASKER

I am able to access the server outside Java from external clients - using both IPs. However, the case here is that the server needs to be used as a client to another server. The other server needs to see different source IPs and I want to be able to control the source IP. This I have not been able to do thus far.
>>However, the case here is that the server needs to be used as a client to another server.

Yes, i'm aware of that, and that's what i was asking you if you'd done successfully - *outside* Java
Avatar of yac678

ASKER

... so I missunderstood your question. Again, I have not been able to have server2 see different source IPs yet and this is the purpose of this discussion.
>> I have not been able to have server2 see different source IPs

In that case, i would put the Java issue on the back burner until you can do that. You might try posting a  supplementary question on it, perhaps trying to do it with netcat, say.
Avatar of yac678

ASKER

I feel that we are really close to a solution with "route". I am still waiting for an answer for 35799882.
Thanks.
but if the destination host is not in the range 195.28.181.1 to 195.28.181.254 - can I leave the above route?

Yes but according to your routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
195.28.181.0    *               255.255.255.0   U     0      0        0 eth0
169.254.0.0     *               255.255.0.0     U     0      0        0 eth0
default         ptco-omcC-195.2 0.0.0.0         UG    0      0        0 eth0

if your destination host is not in the subnet of 195.28.181.0 (i.e. 195.28.181.1 to 195.28.181.254) your packets will use the default route.
default         ptco-omcC-195.2 0.0.0.0         UG    0      0        0 eth0

So you may use the following commands to change the default route..
route del -net 0.0.0.0 netmask 0.0.0.0 gw ptco-omcC-195.2 eth0
route add -net 0.0.0.0 netmask 0.0.0.0 gw ptco-omcC-195.2 eth0:1

Cheers.


Avatar of yac678

ASKER

Looks promissing! I will try this after getting an approval from the hosting company.
Avatar of yac678

ASKER

Another question regarding the above solution: suppose I have an open TCP connection from a client to IP1 (i.e. clientIP:port <-> serverIP1:port). Then I execute the above route commands to change the source IP to IP2. The server would then try to send packets back to the client using the open connection. Would the TCP conection be terminated?
Yes you are right the active connections might break.
You can use netstat to check if there are any active connections
Avatar of yac678

ASKER

I tried executing
route add -net <destination IP> netmask 255.255.255.255 gw 195.28.181.7 eth0:1

but executing "route" afterwards showed:

199.89.233.72.s ptco-omcC-195.2 255.255.255.255 UGH   0      0        0 eth0
195.28.181.0    *               255.255.255.0   U     0      0        0 eth0
169.254.0.0     *               255.255.0.0     U     0      0        0 eth0
default         ptco-omcC-195.2 0.0.0.0         UG    0      0        0 eth0

i.e., I do not see the line I added. In addition, the gateway ptco-omcC-195.2  doesn't answer ping - I see the error "unknown host ptco-omcC-195.2"
In addition, one of the system administrators in the hosting company said that the command I tried executing does not make sense, and that I cannot route traffic through the system itself.
How can I proceed from here?
Avatar of yac678

ASKER

Correction: after exeuting "route -n" I see the following:

Destination          Gateway         Genmask         Flags Metric Ref    Use Iface
<destination IP>   195.28.181.7    255.255.255.255 UGH   0      0        0 eth0
195.28.181.0       0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0         0.0.0.0         255.255.0.0     U     0      0        0 eth0
0.0.0.0                 195.28.181.1    0.0.0.0         UG    0      0        0 eth0

95.28.181.1 is is indeed the default gateway and answers ping. I cannot delete the default gateway because all outgoing traffic must go throu it - including traffic originating at eth0:1 (the second interface)

So it seems that the only problem is that eth0:1 did not stick. I called whatismyip.com from the server and saw that the old IP was still reported instead of 195.28.181.7. Any idea what is going on?
Your default routing is still going to work if you change the following

0.0.0.0                 195.28.181.1    0.0.0.0         UG    0      0        0 eth0

to

0.0.0.0                 195.28.181.1    0.0.0.0         UG    0      0        0 eth0:1

your route entry
<destination IP>   195.28.181.7    255.255.255.255 UGH   0      0        0 eth0
is of no use...
Avatar of yac678

ASKER

After executing
route add -net 0.0.0.0 netmask 0.0.0.0 gw 195.28.181.1 eth0:1
I got two lines with eth0. In other words, the eth0:1 does not stick.
Output of route -n is now:

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
195.28.181.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     0      0        0 eth0
0.0.0.0         195.28.181.1    0.0.0.0         UG    0      0        0 eth0
0.0.0.0         195.28.181.1    0.0.0.0         UG    0      0        0 eth0

Oh OK simply use the following it is sure going to work

iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 195.28.181.7

this will make the source ip of all packets leaving eth0 to have IP as 195.28.181.7
again when you want use the IP 195.28.181.130 simply delete the above entry

iptables -t nat -D POSTROUTING -o eth0 -j SNAT --to 195.28.181.7

Avatar of yac678

ASKER

Interesting. Here's what happened. I executed
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 195.28.181.7
(I read in the man page that "--to-source" is the correct parameter)

Then the java program failed in the line

           InetAddress remoteAddr = InetAddress.getByName(host);
giving an UnknownHostException for whatismyip.com.
I then tried a regular "ping whatismyip.com". The prompt got stuck for a while and then returned with
"ping: unknown host whatismyip.com"
I deleted the line with iptables -t nat -D POSTROUTING -o eth0 -j SNAT --to-source 195.28.181.7
and everything returned back to normal: ping worked and the java program gave the source IP of eth0 as usual.
I tried using the IP of whatismyip.com directly:

           byte[] targetIPBytes = getIPBytes(ipOfWhatIsMyIPServer);
            InetAddress remoteAddr = InetAddress.getByAddress(targetIPBytes);

The client socket was created successfully but the program got stuck on the line
            clientSocket.connect(new InetSocketAddress(remoteAddr, 80));

I am so desparate! Any idea what is going on?
Do you have any more IP tables entry..
I mean can you give me the out put of
iptables -L
iptables -t nat -L

route -n

thanks
Avatar of yac678

ASKER

iptables -L

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:tns-adv
DROP       tcp  --  anywhere             anywhere            tcp dpt:tns-adv
RH-Firewall-1-INPUT  all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:tns-adv
DROP       tcp  --  anywhere             anywhere            tcp spt:tns-adv

Chain RH-Firewall-1-INPUT (2 references)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere            icmp any
ACCEPT     esp  --  anywhere             anywhere
ACCEPT     ah   --  anywhere             anywhere
ACCEPT     udp  --  anywhere             224.0.0.251         udp dpt:mdns
ACCEPT     udp  --  anywhere             anywhere            udp dpt:ipp
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ipp
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:smtp
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:webcache flags:FIN,SYN,RST,ACK/SYN
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ftp
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:https
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited
--------------------------------------------------------------------------------------------------------

iptables -t nat -L

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
-----------------------------------------------------------------------------------

route -n

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
195.28.181.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     0      0        0 eth0
0.0.0.0         195.28.181.1    0.0.0.0         UG    0      0        0 eth0



I strongly doubt if you have a return path
use the iptables command
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 195.28.181.7

and then tracert <destination IP> do you get response from 195.28.181.1
Avatar of yac678

ASKER

I executed
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 195.28.181.7
and then
tracert 195.89.233.72
(the IP of whatismyip.com)
The output:

traceroute to 195.89.233.72 (195.89.233.72), 30 hops max, 40 byte packets
 1   (80.179.92.162)  0.703 ms  0.660 ms *
 2  * * *
 3  * * *
 4  * * *
 5  * * *
 6  * * *
 7  * * *
 8  * * *
 9  * * *
10  * * *
11  * * *
12  * * *
13  * * *
14  * * *
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
23  * * *
24  * * *
25  * * *
26  * * *
27  * * *
28  * * *
29  * * *
30  * * *
Avatar of yac678

ASKER

After removing the iptables line, the output of tracert is:

>> tracert 195.89.233.72
traceroute to 195.89.233.72 (195.89.233.72), 30 hops max, 40 byte packets
 1  80.179.92.162.static.012.net.il.92.92.179.80.in-addr.arpa (80.179.92.162)  0.396 ms  0.386 ms  0.376 ms
 2  CORE-1.PT-SUSITA-tengig9-2.bb.012.net.il (212.199.146.26)  0.245 ms  0.205 ms  0.198 ms
 3  BRDR-PT-ae0-2091.ip4.012.net.il (212.199.73.105)  0.681 ms  0.616 ms  0.547 ms
 4  EDGE-LON-MX-02-so-4-1-0-0.ip4.012.net.il (80.179.165.25)  89.087 ms  72.212 ms  72.410 ms
 5  77.67.61.65 (77.67.61.65)  75.495 ms  75.427 ms  75.353 ms
 6  xe-0-1-0.lon14.ip4.tinet.net (89.149.183.174)  75.904 ms  75.842 ms  75.768 ms
 7  as1273.ip4.tinet.net (77.67.72.138)  84.372 ms !N  84.297 ms !N  84.222 ms !N
Yes got the problem machine/router with IP 80.179.92.162 does not have a route to 195.28.181.7
i.e. if you ping 195.28.181.7 from 80.179.92.162 it will not work
where as ping to 195.28.181.130 from 80.179.92.162 will work.  

Did you get this IP 195.28.181.7 from your ISP? if yes
Execute
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 195.28.181.7
and then
tracert 195.89.233.72

and give them this result so that routing entries are made on 80.179.92.162.
Avatar of yac678

ASKER

Sory for the long delay. I got stuck with the hosting company. I performed what you asked for in the previous message and gave them the result. Here is the reply I got from them:
"The routing definitions above are not correct. 80.179.92.162 is the address of the router you are behind. You cannot define routes in this router, nor do you need to. The problem is in the definitions you are trying to perform."
I did not manage to get them to cooperate, unless I pay some rediculous amount of money for monthly system management.
Could it be that the problem lies somewhere else?
Are other people from the Internet able to ping both your IPs?
195.28.181.130
195.28.181.7

ASKER CERTIFIED SOLUTION
Avatar of expert_tanmay
expert_tanmay
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of yac678

ASKER

This is very odd. I get ping statistics for both IPs:

Pinging 195.28.181.130 with 32 bytes of data:

Reply from 195.28.181.130: bytes=32 time=18ms TTL=58
Reply from 195.28.181.130: bytes=32 time=14ms TTL=58
Reply from 195.28.181.130: bytes=32 time=16ms TTL=58
Reply from 195.28.181.130: bytes=32 time=15ms TTL=58

Ping statistics for 195.28.181.130:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 14ms, Maximum = 18ms, Average = 15ms

Pinging 195.28.181.7 with 32 bytes of data:

Reply from 195.28.181.7: bytes=32 time=15ms TTL=58
Reply from 195.28.181.7: bytes=32 time=15ms TTL=58
Reply from 195.28.181.7: bytes=32 time=14ms TTL=58

Ping statistics for 195.28.181.7:
    Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 14ms, Maximum = 15ms, Average = 14ms

Could you tell me the IP your pinging from? Maybe the hosting provider will need this.
My IP is 203.127.84.23 ask any friend of yours to ping may be from his home or office network ....
Any way what was your IP when u pinged 195.28.181.7 ?
Avatar of yac678

ASKER

I asked my brother who lives in the US to ping the second IP and he got the same problem as yours. The hosting company asked for the results of tracert and I provided them the following:

Tracing route to ptco-omcC-195.28.181.130.012.net.il [195.28.181.130]
over a maximum of 30 hops:

  1     1 ms     1 ms     1 ms  192.168.1.1
  2     9 ms     8 ms    10 ms  10.68.32.1
  3     9 ms     9 ms    11 ms  gig-3-0-6-nycmnyw-rtr2.nyc.rr.com [24.29.113.158
]
  4     9 ms    11 ms     9 ms  tg-1-0-0-nycmnytg-jun01.nyc.rr.com [24.29.104.12
6]
  5    54 ms     7 ms     9 ms  cpe-24-29-148-66.nyc.res.rr.com [24.29.148.66]
  6     8 ms     9 ms     9 ms  ae-4-0.cr0.nyc30.tbone.rr.com [66.109.6.78]
  7    15 ms    14 ms    13 ms  ae-4-0.cr0.dca20.tbone.rr.com [66.109.6.28]
  8    17 ms    13 ms    13 ms  107.14.19.135
  9    15 ms    14 ms    15 ms  tenge13-2.br03.ash01.pccwbtn.net [63.218.92.77]

 10    19 ms    15 ms    15 ms  TenGE10-0.cr04.ash01.pccwbtn.net [63.218.44.53]

 11   105 ms   105 ms   105 ms  TenGE2-1.br02.frf02.pccwbtn.net [63.218.14.206]

 12   108 ms   102 ms   101 ms  EDGE-FRA-01-ae3-51.ip4.012.net.il [80.179.166.16
3]
 13   103 ms   109 ms   103 ms  EDGE-FRA-02-ae3-100.ip4.012.net.il [80.179.166.7
0]
 14   173 ms   176 ms   171 ms  BRDR-CORE-MR-so-9-1-0-0.ip4.012.net.il [80.179.1
66.30]
 15   174 ms   171 ms   167 ms  BRDR-CORE-MR-ae1-3024.ip4.012.net.il [212.199.5.
106]
 16   169 ms   173 ms   177 ms  CORE-PT-xe-7-3-1.ip4.012.net.il [212.199.6.85]
 17   171 ms   171 ms   169 ms  DC-PT-01-te1-2.ip4.012.net.il [212.199.146.25]
 18   169 ms   165 ms   164 ms  ptco-omcC-195.28.181.130.012.net.il [195.28.181.
130]

Trace complete.

Tracing route to ptco-omcC-195.28.181.7.012.net.il [195.28.181.7]
over a maximum of 30 hops:

  1     1 ms     1 ms     1 ms  192.168.1.1
  2     7 ms     7 ms     7 ms  10.68.32.1
  3    13 ms     8 ms     9 ms  gig-0-3-0-21-nycmnyw-rtr2.nyc.rr.com [24.168.138
.41]
  4     8 ms     9 ms     9 ms  tg-1-0-0-nycmnytg-jun01.nyc.rr.com [24.29.104.12
6]
  5     9 ms     9 ms     7 ms  cpe-24-29-148-66.nyc.res.rr.com [24.29.148.66]
  6     8 ms     9 ms     9 ms  ae-4-0.cr0.nyc30.tbone.rr.com [66.109.6.78]
  7    25 ms    14 ms    15 ms  ae-4-0.cr0.dca20.tbone.rr.com [66.109.6.28]
  8    24 ms    13 ms    14 ms  107.14.19.135
  9    58 ms    15 ms    14 ms  tenge13-2.br03.ash01.pccwbtn.net [63.218.92.77]

 10   109 ms   109 ms   107 ms  TenGE2-1.br02.frf02.pccwbtn.net [63.218.14.206]

 11     *        *        *     Request timed out.
 12     *        *        *     Request timed out.
 13     *        *        *     Request timed out.
 14     *        *        *     Request timed out.
 15     *        *        *     Request timed out.
 16     *        *        *     Request timed out.
 17     *        *        *     Request timed out.
 18     *        *        *     Request timed out.
 19     *        *        *     Request timed out.
 20     *        *        *     Request timed out.
 21     *        *        *     Request timed out.
 22     *        *        *     Request timed out.
 23     *        *        *     Request timed out.
 24     *        *        *     Request timed out.
 25     *        *        *     Request timed out.
 26     *        *        *     Request timed out.
 27     *        *        *     Request timed out.
 28     *        *        *     Request timed out.
 29     *        *        *     Request timed out.
 30     *        *        *     Request timed out.

Trace complete.
Avatar of yac678

ASKER

They fixed it!! They said that from some reason the second IP was blocked abroad. Now everything worked. The Java solution worked and I got the second IP reported by whatismyip.com.
The iptables solution worked as well.