Here you can find the source of createDatagramSocket(InetAddress addr, int port)
Parameter | Description |
---|---|
addr | The InetAddress to which the socket should be bound. If null, the socket will not be bound. |
port | The port which the socket should use. If 0, a random port will be used. If > 0, but port is already in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. |
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception
//package com.java2s; import java.net.BindException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class Main { public static final int MAX_PORT = 65535; /**/*from w w w. j av a 2 s . c om*/ * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception { DatagramSocket sock = null; if (addr == null) { if (port == 0) { return new DatagramSocket(); } else { while (port < MAX_PORT) { try { return new DatagramSocket(port); } catch (SocketException bind_ex) { // port already used if (treatAsBindException(bind_ex)) { // GemStone Addition port++; } else { throw bind_ex; } } catch (Exception ex) { throw ex; } } } } else { if (port == 0) port = 1024; while (port < MAX_PORT) { try { return new DatagramSocket(port, addr); } catch (SocketException bind_ex) { // port already used if (treatAsBindException(bind_ex)) { // GemStone Addition port++; } else { throw bind_ex; } } catch (Exception ex) { throw ex; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static boolean treatAsBindException(SocketException se) { if (se instanceof BindException) { return true; } final String msg = se.getMessage(); return (msg != null && msg.contains("Invalid argument: listen failed")); } }