Java Socket bind() and connect() method

Hi,
I'm running a windows xp machine and have set it up (using the raspppoe protocol) to make simultaneous dial-up connections to the internet. Each of these dial-up connections then has its own IP address.
When I create a new Socket, bind it to one of these IP addresses and invoke the connect() method (to a remote host), the socket times out. Only when i bind it to the most recent dial-up connection that has been established, the socket connects.
I'm welcome for any ideas :)
thanks

If you'll excuse the lengthy post it has alot of code and outputs :)
Ok Wingate really doesnt have much to do with the program, let me get back to the point and then post the code I have.
Goal of the application:
To use multiple simultaneous dial-up interfaces connected to the internet by binding each of them (using Socket class .bind() method) to its associated Socket object.
Method:
I use the RASPPPOE protocol for Windows XP to allow these multiple simultaneous ADSL dial-up connections. Each of these dial-up instances gets assigned an IP address. I use the NetworkInterface class to retrieve these interfaces/IP addresses and then run a loop to bind each Socket to its associated interface.
The code I am pasting here is over-simplified and is just to illustrate what it is i'm trying to do.
Firstly, this is a cut & paste of the tutorial from the Java website on how to list the Network interfaces on an operating system and the associated output:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNIFs
    public static void main(String args[]) throws SocketException
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();       
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);       
    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();       
        for (InetAddress inetAddress : Collections.list(inetAddresses))
            out.printf("InetAddress: %s\n", inetAddress); 
        out.printf("Up? %s\n", netint.isUp());
        out.printf("Loopback? %s\n", netint.isLoopback());
        out.printf("PointToPoint? %s\n", netint.isPointToPoint());
        out.printf("Supports multicast? %s\n", netint.supportsMulticast());
        out.printf("Virtual? %s\n", netint.isVirtual());
        out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress()));
        out.printf("MTU: %s\n", netint.getMTU());       
        out.printf("\n");
}For which the output is:
Display name: MS TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1
Up? true
Loopback? true
PointToPoint? false
Supports multicast? true
Virtual? false
Hardware address: null
MTU: 1520
Display name: Intel(R) PRO/Wireless 3945ABG Network Connection - Packet Scheduler Miniport
Name: eth0
InetAddress: /192.168.1.10
Up? true
Loopback? false
PointToPoint? false
Supports multicast? true
Virtual? false
Hardware address: [0, 25, -46, 93, -13, 86]
MTU: 1500
Display name: WAN (PPP/SLIP) Interface
Name: ppp0
InetAddress: /196.209.42.125
Up? true
Loopback? false
PointToPoint? true
Supports multicast? true
Virtual? false
Hardware address: null
MTU: 1492
Display name: WAN (PPP/SLIP) Interface
Name: ppp1
InetAddress: /196.209.248.25
Up? true
Loopback? false
PointToPoint? true
Supports multicast? true
Virtual? false
Hardware address: null
MTU: 1492
Display name: WAN (PPP/SLIP) Interface
Name: ppp2
InetAddress: /196.209.249.4
Up? true
Loopback? false
PointToPoint? true
Supports multicast? true
Virtual? false
Hardware address: null
MTU: 1492The part to take notice of is the three WAN (PPP/SLIP) Interfaces named ppp0, ppp1 and ppp2. They are simultaneous dial-up connections to the internet, each with a unique IP. I will now attempt to use one of these interfaces to establish a connection to www.google.com on port 80 (purely for illustration).
In the code printed below, I simply hard coded the above listed IP address of the interface for simplification:
import java.net.*;
import java.io.*;
public class SockBind {
     private Socket connection;     
     private void start() throws IOException
          while (true)
               try {
                    connection = new Socket();
                    connection.bind(new InetSocketAddress("196.209.42.125", 12345));
                    connection.connect(new InetSocketAddress("www.google.com", 80));
                    connection.close();
               } catch (SocketException e) {
                    System.err.println(e.getMessage());
     public static void main(String args[])
          try {
               SockBind s = new SockBind();
               s.start();
               System.out.println("Program terminated.");
          } catch (IOException e) {
               e.printStackTrace();
               System.exit(1);
}Once the program reaches the connection.connect() method, it pauses a while until it throws a SocketException with a "timed out" message. I have already tested the dial-up connection (using a wingate, which is irrelevant) just to confirm that the connection is in working order.
EJP if you have any suggestions I will welcome it, many thanks :)

Similar Messages

  • Creating DAO layer from java beans(setter and getter methods)

    Can anybody explain me how to create an adapter layer (DAO layer) from java beans with no connection and transaction code inside DAO layer?

    Sure, have another layer do the transaction work.
    Your DAO would make us of this layer.

  • Jave servlets- doget() and dopost() methods.

    Iam trying to learn servlets but got confused on these doget() and dopost() methods usage. I just want to know generally what does these methods do in general (like the doget() sets the header..but what about dopost()?). I saw some example code where doget() is called within a dopost()method so Iam not clear about their purposes.
    I'd appreciate any help possible. Thank you.

    The doPost() and doGet() (also doHead() etc.) methods are all designed to handle specific HTTP request types. eg: doGet() handles HTTP GET requests (requests caused by common HTML links or typing a URL in your browser's address bar) while POST handles HTTP POST requests (commonly generated by HTML form submissions).
    When you see an example of a serlvet's doGet() being called within it's doPost(), it is because, at least for part of the processing, the servlet will be treating the two request types the same way.

  • Java Pet Store and connection pooling

    Hi. Does the Java Petstore version 1.2 use connection pooling? I know in the database.properties file it has the following variables:
    Pool.MaximumActiveConnections=10
    Pool.MaximumIdleConnections=5
    Pool.MaximumCheckoutTime=120000
    Pool.TimeToWait=10000
    Pool.PingEnabled=false
    Pool.PingQuery=select * from dual
    Pool.PingConnectionsOlderThan=0
    Pool.PingConnectionsNotUsedFor=0
    Pool.QuietMode=true
    To me this seems like it is using connection pooling. However, on our server, we are continually running out of connections and I KNOW that our other apps ARE using connection pooling. So I'm just wondering if someone can confirm with me that the Java Pet Store is in fact using connection pooling.
    Thanks in advance,
    Dylan

    I forgot to mention that I'm using the Ibatis version of the JPetstore.

  • DatagramSocket read and write methods

    Hi,
    I am trying to implement a client/server schame via NIO DatagramChannel.
    I manage to make it work with the methods send/receive. but i am not able to make it work in "connected" mode via write/read method.
    i bind and connect like this;
    this.channel = DatagramChannel.open();
    this.channel.configureBlocking(false);
    this.channel.socket().bind(hostAdr);
    this.channel.connect(destAddress);
    then i receive messages like this:
    ByteBuffer theReceiveDataByteBuffer = ByteBuffer.allocateDirect(5000);
    Charset charset = Charset.forName("ISO-8859-1");
    StringBuffer buffer = new StringBuffer();
    String[] retval = new String[2];
    while (flag) {
    try {
    Int value = receiverChannel.read(theReceiveDataByteBuffer);
    long time = System.currentTimeMillis();
    } catch (IOException e) {
    Thread.currentThread().interrupt();
    flag = false;
    I send via the write method, it seems i manage to send but i receive nothing...
    How to code this kind of scheme with write/read ?
    thank you
    Sebastien
    Edited by: sepi_seb on Nov 29, 2007 10:06 AM

    Well (a) you're spinning madly burning up the CPU in a non-blocking read loop; (b) if this is the complete code you don't have any way of knowing whether you received anything or not; and (c) you're completely suppressing any IOExceptions that may be occurring, so you can't see anything that's going wrong.
    So:
    (a) don't use non-blocking mode, or use a Selector to tell you when OP_READ is ready for the channel;
    (b) try breaking out of the loop when you've received something, i.e. when the bytecount returned from read() > 0; and then display something;
    (c) when you get an exception it contains a valuable message and an equally valuable stack trace. Don't just ignore them.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Use of synchronized queue for java socket communications

    Hi all,
    We have a need for a server socket application (stand alone java application) to process just one command per time coming from a java socket client (JSP Web application). There are a lot of users accessing the java socket client, but the server socket can only handle one command per time, so there is a need of a queue type, so users will have to wait for their time.
    We've been told that we can use "synchronized Queue", but we don't know what it is and how to use. A URL, book etc. with sample code would assist us, since we are new to both java socket communication and queue of commands.
    Can anyone assist us
    cheers
    Trajano
    P.S.
    The server socket java application has two threads:
    1st thread handles the java socket communication;
    2nd thread is a RS-232 serial driver that communicates to several micro-controllers connected on a multi-drop.
    JSP web app client socket users can issue various commands at the same time to the java server socket app, however the server can only service one command per time (just one RS-232 COM1 serial port available). The commands have to somehow be added to a queue for processing.

    I do not have the experience to offer advice. But I just happened to be reading today about Collections.synchronizedList.
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Collections;
    public class Queue {
       private List queue;
       public Queue() {
          queue = Collections.synchronizedList(new LinkedList());
       public Object removeItem() throws InterruptedException {
          synchronized (queue) {
             while (queue.isEmpty())
                queue.wait();
             return queue.remove(0);
       public void addItem(Object item) {
          synchronized (queue) {
             queue.add(item);
             queue.notifyAll();
    class Test {
       public static void main(String[] args) {
          final Queue queue = new Queue();
          //start a thread to process items from the queue
          Runnable work = new Runnable() {
             public void run() {
                try {
                   Object item = queue.removeItem();
                   //do something with item
                } catch (InterruptedException e) {
                   //handle this
          Thread worker = new Thread(work);
          worker.start();
    }Reference: Java Thread Programming, Paule Hyde
    Also, here is Doug Lea's library,
    http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html

  • Over riding hashtable get and put method

    Hi all
    Anyone have any idea about over ride HashTable get() and put(). Is it possible to over ride HashTable methods.

    Yes_me wrote:
    I want to change the structure of the java HashTable get and put method. As put method is having two object parameters I want to send one more parameter as String to it. Is it possible to change the structure in this way.What would you want to be returned when calling get()? I would go with the suggestion to create a class to keep that information. If you really want to, you can completely hide that information class inside your extended HashTable. You could create an overloaded put method that takes three parameters and then creates an instance of the information class and put that into the map. If you only want the data for display only, the get method could get the information class mapped to the given key, then simply return a nicely formatted String containing the two values.

  • Binding and displaying data to table in webdynpro java

    hi all,
    i want to know how to bind the output values to table in webdynpro java.
    i know how to bind values in context to table,but if we want to display the values from database(back end ) and display in table present in the view.
    eg: i have table in view and want to get values from backend(SQL server) and display it in that table.
    plz help me to know ..
    thanks
    sirisha

    Hi Saisirisha,
    Try this.
    1> Take a Value Node(Employee) cardinality 0..n.
    Employee Structure
    Employee
    |------Surname(Attribute)
    |------FirstName(Attribute)
    |------Category(Attribute)
    2> Bind this value node(Employee) in the View datasource of table.
    3> Try the code inside wdDoInit method.
    try {
         // Load the JDBC-ODBC bridge
         Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
         // specify the ODBC data source's URL
         String url = "jdbc:odbc:SSPer";
         // connect
         Connection con = DriverManager.getConnection(url,"North","Ken");
         // create and execute a SELECT
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery
         ("SELECT Surname,FirstName,Category FROM Per");
         while (rs.next()) {
         // get current row values
         String Surname = rs.getString(1);
         String FirstName = rs.getString(2);
         int Category = rs.getInt(3);
         //create table row and add the value in the table
         IPrivate<Put View Name>.IEmployeeElement empElm = wdContext.createEmployeeElement();
            empElm.setSurname(Surname);
         empElm.setFirstName(FirstName);
         empElm.setCategory(Category);
         wdContext.nodeEmployee().addElement(empElm);
         // close statement and connection
         stmt.close();
         con.close();
    } catch (java.lang.Exception ex) {
         wdComponentAPI.getMessageManager().reportException("Exception : "ex.getMessage()+,true);
    http://www.developer.com/java/data/article.php/3417381
    Regards,
    Mithu

  • Java Sockets and Output Streams

    Hi All,
    I am beginning sockets programming and I have a problem. If there is a server listening in the background for incoming connections and say for example 4 client programs programs which we shall call client1...client4 connect. How best can I capture the output streams associated with these newly created sockets so that the server can send back isome nformation to say clients1 and client4 only which is not seen by clients 2 and 3. Similarly I would like the server to send some infor to clients 2 and 3 only which is not seen by client1 and client 4.
    Currently I have the server listening part as shown below, but not too sure how to add DISTINCT output streams for 1 and 4 on one hand and 2 and 3 on the other.
    Thanks:
    // bind socket to a port number
    ServerSocket serverSocket = new ServerSocket(portNo);
    // create socket to listen to client connection
    while (true) {
    //listen to an incoming connection
    System.out.println("chatroom server waiting for incoming connections");
    Socket incomingSocket = serverSocket.accept();
    //launch new thread to take care of new connection
    chatRoomThread chatThread = new chatRoomThread(incomingSocket);
    chatThread.start();
    //go back and wait for next connection
    Please help.
    Thanks,
    Bleak

    HouseofHunger wrote:
    yes thats exactly the way I have my in and out streams, in the run method, but that doesn't help me in filtering traffic, in other words I am saying 2 clients, client1 and client4 for example should share a common in and out stream so that they will see eact other's messages... makes sense.....?No, doesn't make sense. That's the wrong design. Each socket should have its own input and output stream (yes, I know, that's been said several times before). If messages going to client1 should also be sent to client4, then whatever writes the messages to client1's output stream must also write them to client4's output stream. Trying to make those two output streams actually be the same output stream is the wrong way to do that. Just have the controller send the messages to whoever is supposed to get them.

  • Problem socket.bind() with multiple modems and multiple IPs

    I've connected 2 or more modems in Windows control panel and made up windows dail ups. Then I dail up each modem and obtain the local DHCP IPs of each modem.
    My target is : to set up sockets using separate modems.
    the code is like: create a socket instance , and use Socket.bind()method to bind the socket to a specified modem's local IP , then do socket.connect().
    but the problem is : although there are several modem dail ups and at the same time I bind each socket to different IPs , the program always connect via the first modem dailed up.
    Does Socket.bind() method really bind the socket connection to the IP's or hardwares?

    I think you are trying to use a Socket where you want a ServerSocket to accept the incoming connection. Check this out (I have underlined what
    should interest you):
    public ServerSocket(int port, int queueLength) throws IOException, BindException
    This constructor creates a ServerSocket on the specified port with a queue length of your choosing. If the machine has multiple network interfaces or IP addresses, then it listens on this port on all those interfaces and IP addresses. The queueLength argument sets the length of the queue for incoming connection requests--that is, how many incoming connections can be stored at one time before the host starts refusing connections. Some operating systems have a maximum queue length, typically five. If you try to expand the queue past that maximum number, the maximum queue length is used instead. If you pass 0 for the port number, the system selects an available port.
    For example, to create a server socket on port 5,776 that would hold up to 100 incoming connection requests in the queue, you would write:
    try {
      ServerSocket httpd = new ServerSocket(5776, 100);
    catch (IOException e) {
      System.err.println(e);
    }The constructor throws an IOException (specifically, a BindException) if the socket cannot be created and bound to the requested port. An IOException when creating a ServerSocket almost always means one of two things. Either the specified port is already in use, or you do not have root privileges on Unix and you're trying to connect to a port from 1 to 1,023.
    So once you receive a connection, it looks like it is up to you parse any
    relevant info you want out of the Socket you get from ServerSocket.accept();
    -Cludge

  • Object binding and ISDN connections

    Fort&eacute; users,
    the problem is the following:
    we have a win95 client running remotely and connected to a server
    (ultrasparc solaris) via an ISDN line.
    The application works normally for almost all applicative functionality and
    Fort&egrave; mechanisms (events posted from clients included) except one: the
    task.Part.ObjectLocationMgr.bindObject method.
    We use the task.Part.ObjectLocationMgr.bindObject method to bind an object
    on a client A to an object on a client B (we use this direct communication
    link from one client to another to implement a sort of 'remote' control of
    client B from the client A).
    This solution normally WORKS when A e B are in our in-house LAN and NOT
    when A or B connect to the rest of the system via an ISDN line! (I have not
    tried a modem connection). I repeat all other functionalities works
    normally.
    Has someone encountered this problem before? Has someone an idea to solve
    the problem or to understand the reason of this behavoiur?
    We are using Fort&eacute; 2.0.H.1.
    Thank you very much in advance.
    Corrado Tamietti (Tel : +39 11 3168.733)
    CSI Piemonte (Consorzio per il Sistema Informativo)
    C.so Unione Sovietica 216
    I-10134 Torino (ITALY)

    hi,
    For that you have to create custom BO(using SWO1) which supertype is current BO.
    then in that ZBO you can change the value using below code:
    in top of programme include<CNTN01>.
    then to get that element use :
    swc_get_element container 'PERNR' empid.
    then process on it or create new container element using
    swc_create_element 'PERNR' empid.
    then fill it using
    swc_set_element container 'IT_EMP' IT_EMP.
    or if it is multi line element use:
    swc_set_table
               lt_event_container
                 'ZMAIL' it_TEXT1.
    don't forget to include<cntn01>.
    then copy existing standard task(using PFTC) and define necessary container element and do binding!
    Hope magic Works!
    Regards,
    Purvesh Patel.

  • Connect Java with SSRS URL Access method

    I am trying to connect SSRS with Java to display the reports in a browser.
    My application is java 1.6 Swing application and use Applet.I read the article
    http://www.javaworld.com/javaworld/jw-01-2005/jw-0110-sqlrs.html?page=4
    But I am not able to understand why do we need the servlets the authors has mentioned.
    I am able to connect and get back the report in pdf format without these servlets .Also what sort of access will be required for this.
    Will all external users need access to the report server.
    Some one please help
    Any other suggestion for connection SSRS with JAVA .I have tried webservice method and it dint work either now I am planning for url access
    but need help with this
    Thanks

    Can anyone please help.I can provide any more info if needed.I tried the URL method but I get no response in my stream.
    I can post the code i am using in the servlet.

  • Connecting to http web site using java socket

    Hi,
    Sockets in Java I believe are reusable. Once created, it can be used to send a request using its input stream and get back a response using the output stream. My problem is I am trying to connect to a website using java socket but I am unable to get a response (though the same works fine I use URL and URLConnection). Can anyone tell me whats wrong? Below is the client program:
    public class HttpAdapterTest {
         public static void main(String[] args) {
              try {
                   Socket socket = new Socket("www.google.com", 80);
                   BufferedWriter out = new BufferedWriter(
                                  new OutputStreamWriter(socket.getOutputStream()));
                   out.write("GET /help/basics.html HTTP/1.1");
                   out.flush();
                   BufferedReader in = new BufferedReader(
                                            new InputStreamReader(ucon.getInputStream()));
                   String line = null;
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                   in.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Look at the JSSE examples. You need to setup a key store, add the jsse jars to your classpath, yadda, yadda, yadda....

  • Java sockets and winsock

    when I use java socket to talk to my proxy, without going through a winsock, my java applet runs fine. However, when I patch winsock in between my java gui and my other proxy, I dont receive anything in the gui. I snoop at packets coming from my other proxy through winsock to my gui and the data is all there. I just cannot receive it.
    I use java class DatagramSocket() to establish a socket connection and use class DatagramPacket to get the packets coming. This works if I dont go through a ms proxy.
    Can anyone tell me why?

    How can you snoop at packets comming? I need to know so bad. :-)
    Thank you

Maybe you are looking for

  • Can i home share a music libary from one device to another?

    im trying to combine my music libary with my brothers is there a way to do this through home sharing or itunes match

  • Import from minidisc

    My wife has tons of stuff on minidisc and wants to import to the iMac to burn CDs. What is the best way to get songs off her dedicated minidisc player - which doesn't have audio out - into the Mac? I've read that it's possible to use the headphone so

  • AAHH Kernel Panic!

    When ever i watch a video on you tube for more than 10 mins i either get a Kernel Panic or safari unexpectingly quitting. Also the machine randomly restarts sometimes too. This has only just started happening when i did the most recent airport and se

  • I accidently removed Firefox and all my settings, how do I get it all back?

    I was removing another program in add or remove and accidently removed firefox now I have lost everything, is there any way of getting it all back? ff3.6.15 wxp

  • EBS search String

    Hi , We use MT940 with both field 86 and without . We have problem  that bank do not put either paymnet document number or vendor number in bank statement . They put vendor / customer name in the statement with External Transaction . But that externa