Java Code Examples for java.net.datagramsocket#connect()
The following examples show how to use
java.net.datagramsocket#connect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatagramChannelTest.java From j2objc with Apache License 2.0 | 6 votes |
private void assertSocketActionAfterConnect(DatagramSocket s) throws IOException { assertEquals(s.getPort(), datagramSocket1Address.getPort()); try { s.connect(datagramSocket2Address); fail(); } catch (IllegalStateException expected) { } assertTrue(this.channel1.isConnected()); assertTrue(s.isConnected()); // not changed assertEquals(s.getPort(), datagramSocket1Address.getPort()); s.disconnect(); assertFalse(this.channel1.isConnected()); assertFalse(s.isConnected()); s.close(); assertTrue(s.isClosed()); assertFalse(this.channel1.isOpen()); }
Example 2
Source File: PortScanUDP.java From AndroidNetworkTools with Apache License 2.0 | 6 votes |
/** * Check if a port is open with UDP, note that this isn't reliable * as UDP will does not send ACKs * * @param ia - address to scan * @param portNo - port to scan * @param timeoutMillis - timeout * @return - true if port is open, false if not or unknown */ public static boolean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { try { byte[] bytes = new byte[128]; DatagramPacket dp = new DatagramPacket(bytes, bytes.length); DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(timeoutMillis); ds.connect(ia, portNo); ds.send(dp); ds.isConnected(); ds.receive(dp); ds.close(); } catch (SocketTimeoutException e) { return true; } catch (Exception ignore) { } return false; }
Example 3
Source File: UpnpSettingsResource.java From ha-bridge with Apache License 2.0 | 6 votes |
private InetAddress getOutboundAddress(String remoteAddress, int remotePort) { InetAddress localAddress = null; try { DatagramSocket sock = new DatagramSocket(); // connect is needed to bind the socket and retrieve the local address // later (it would return 0.0.0.0 otherwise) sock.connect(new InetSocketAddress(remoteAddress, remotePort)); localAddress = sock.getLocalAddress(); sock.disconnect(); sock.close(); sock = null; } catch(Exception e) { ParseRoute theRoute = ParseRoute.getInstance(); try { localAddress = InetAddress.getByName(theRoute.getLocalIPAddress()); } catch(Exception e1) {} log.warn("Error <" + e.getMessage() + "> on determining interface to reply for <" + remoteAddress + ">. Using default route IP Address of " + localAddress.getHostAddress()); } log.debug("getOutbountAddress returning IP Address of " + localAddress.getHostAddress()); return localAddress; }
Example 4
Source File: PortScanUDP.java From HttpInfo with Apache License 2.0 | 6 votes |
public static PortBean.PortNetBean scanAddress(InetAddress ia, int portNo, int timeoutMillis) { PortBean.PortNetBean portNetBean = new PortBean.PortNetBean(); Long time = System.currentTimeMillis(); try { byte[] bytes = new byte[128]; DatagramPacket dp = new DatagramPacket(bytes, bytes.length); DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(timeoutMillis); ds.connect(ia, portNo); ds.send(dp); ds.isConnected(); ds.receive(dp); ds.close(); portNetBean.setConnected(true); } catch (SocketTimeoutException e) { } catch (Exception ignore) { } portNetBean.setPort(portNo); portNetBean.setDelay(System.currentTimeMillis() - time); return portNetBean; }
Example 5
Source File: TransportFactory.java From perfmon-agent with Apache License 2.0 | 5 votes |
/** * Returns new UDP Transport instance * connected to specified socket address * * @param addr * @return connected Transport * @throws IOException */ public static Transport UDPInstance(SocketAddress addr) throws IOException { DatagramSocket sock = new DatagramSocket(); sock.setSoTimeout(getTimeout()); sock.connect(addr); StreamTransport trans = new StreamTransport(); trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock)); trans.setAddressLabel(addr.toString()); return trans; }
Example 6
Source File: UDPReceiverTest.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void sendSocketBufferSize() throws IOException { DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0); DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT)); datagramSocket.send(datagramPacket); datagramSocket.close(); }
Example 7
Source File: TestDatagramSocketServlet.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
private void testSocketImplConstructor(HttpServletResponse response) throws IOException, AssertionFailedException { MockSocketImpl mockImpl = new MockSocketImpl(); DatagramSocket socket = new DatagramSocket(mockImpl) {}; // Accessing protected constructor. try { socket.connect(InetAddress.getByName("10.1.1.1"), 9999); assertTrue( "Expected SecurityException when not using AppEngineDatagramSocketImpl.", false, response); } catch (SecurityException e) { // OK } }
Example 8
Source File: NetUtil.java From incubator-pinot with Apache License 2.0 | 5 votes |
/** * Get the ip address of local host. */ public static String getHostAddress() throws SocketException, UnknownHostException { DatagramSocket ds = new DatagramSocket(); ds.connect(InetAddress.getByName(DUMMY_OUT_IP), 80); InetAddress localAddress = ds.getLocalAddress(); if (localAddress.getHostAddress().equals("0.0.0.0")) { localAddress = InetAddress.getLocalHost(); } return localAddress.getHostAddress(); }
Example 9
Source File: NetworkPackageQueueHandler.java From PowerSwitch_Android with GNU General Public License v3.0 | 5 votes |
private void send(NetworkPackage networkPackage) throws Exception { switch (networkPackage.getCommunicationType()) { case UDP: InetAddress host = InetAddress.getByName(networkPackage.getHost()); int port = networkPackage.getPort(); socket = new DatagramSocket(null); socket.setReuseAddress(true); socket.connect(host, port); byte[] messageBuffer = networkPackage.getMessage().getBytes(); DatagramPacket messagePacket = new DatagramPacket(messageBuffer, messageBuffer.length, host, port); socket.send(messagePacket); Log.d("UDP Sender", "Host: " + host.getHostAddress() + ":" + port + " Message: \"" + new String(messageBuffer) + "\" sent."); socket.disconnect(); socket.close(); break; case HTTP: URL url = new URL("http://" + networkPackage.getHost() + ":" + networkPackage.getPort() + "/" + networkPackage.getMessage()); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); } finally { urlConnection.disconnect(); } break; } }
Example 10
Source File: NetworkUtils.java From africastalking-android with MIT License | 5 votes |
static String determineLocalIp() { try { DatagramSocket s = new DatagramSocket(); s.connect(InetAddress.getByName("192.168.1.1"), 80); return s.getLocalAddress().getHostAddress(); } catch (IOException e) { Log.e("determineLocalIp()", e.getMessage() + ""); // dont do anything; there should be a connectivity change going return null; } }
Example 11
Source File: AcceptorTest.java From game-server with MIT License | 5 votes |
public void testUDP() throws Exception { DatagramSocket client = new DatagramSocket(); client.connect(new InetSocketAddress("127.0.0.1", port)); client.setSoTimeout(500); byte[] writeBuf = new byte[16]; byte[] readBuf = new byte[writeBuf.length]; DatagramPacket wp = new DatagramPacket(writeBuf, writeBuf.length); DatagramPacket rp = new DatagramPacket(readBuf, readBuf.length); for (int i = 0; i < 10; i++) { fillWriteBuffer(writeBuf, i); client.send(wp); client.receive(rp); assertEquals(writeBuf.length, rp.getLength()); assertTrue(Arrays.equals(writeBuf, readBuf)); } try { client.receive(rp); fail("Unexpected incoming data."); } catch (SocketTimeoutException e) { } client.close(); }
Example 12
Source File: UdpSource.java From Azzet with Open Software License 3.0 | 5 votes |
@Override public InputStream getStream( String request ) throws Exception { byte[] path = getAbsolute( request ).getBytes(); DatagramPacket outgoing = new DatagramPacket( path, path.length ); DatagramPacket incoming = new DatagramPacket( new byte[packetSize], packetSize ); DatagramSocket s = new DatagramSocket(); s.connect( address ); s.send( outgoing ); s.receive( incoming ); return new DatagramInputStream( incoming.getData(), 0, incoming.getLength(), s ); }
Example 13
Source File: YokeActivity.java From yoke-android with MIT License | 5 votes |
public void openSocket(String host, int port) { currentHost = host; currentPort = port; log(String.format(res.getString(R.string.log_opening_udp), host, port)); try { mSocket = new DatagramSocket(0); mSocket.connect(InetAddress.getByName(host), port); log(res.getString(R.string.log_open_udp_success)); String url = "file://" + currentMainPath.toString(); YokeActivity.this.runOnUiThread(() -> { mTextView.setText(res.getString(R.string.toolbar_connected_to)); if (currentMainPath.exists()) { wv.loadUrl(url); } else { Toast.makeText(YokeActivity.this, String.format( res.getString(R.string.toast_download_layout_first), res.getString(R.string.menu_upgrade_layout), res.getString(R.string.toolbar_reconnect) ), Toast.LENGTH_LONG).show(); } }); log(String.format(res.getString(R.string.log_loading_url), url)); } catch (SocketException | UnknownHostException e) { mSocket = null; currentHost = null; YokeActivity.this.runOnUiThread(() -> { mSpinner.setSelection(mAdapter.getPosition(NOTHING)); }); logError(String.format(res.getString(R.string.error_open_udp_error), host, port), e); } }
Example 14
Source File: UdpSocketTest.java From pinpoint with Apache License 2.0 | 5 votes |
public void createUdpSocket() throws IOException { DatagramSocket so = new DatagramSocket(); // so.bind(new InetSocketAddress("localhost", 8081)); // DatagramSocket receiver = new DatagramSocket(new InetSocketAddress("localhost", 8082)); // receiver.bind(new InetSocketAddress("localhost", 8082)); so.connect(new InetSocketAddress("localhost", 8082)); so.send(new DatagramPacket(new byte[10], 10)); // receiver.receive(newDatagramPacket(1000)); so.close(); }
Example 15
Source File: NettyUdpReceiverTest.java From pinpoint with Apache License 2.0 | 5 votes |
private void start() throws IOException, InterruptedException { DatagramSocket so = new DatagramSocket(); so.connect(new InetSocketAddress("127.0.0.1", PORT)); int count = 1000; for (int i = 0 ; i< count; i++) { byte[] bytes = new byte[100]; DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); so.send(datagramPacket); Thread.sleep(10); } so.close(); }
Example 16
Source File: UdpClient.java From mts with GNU General Public License v3.0 | 4 votes |
public void run() { try { DatagramSocket datagramSocket = new DatagramSocket(0/*(int) UdpTest.SERVER_PORT + 1*/, Inet4Address.getByName(UdpTest.SERVER_HOST)); //DatagramSocket datagramSocket = new DatagramSocket(null); // null->unbound System.out.println("UdpClient: client ready"); boolean connect = false; // true ; "connect�" ou non byte[] data = new byte[(int)UdpTest.MSG_SIZE]; for(int i=0; i<data.length; i++) { data[i] = (byte)i;// 0; } DatagramPacket datagramPacket = new DatagramPacket(data,data.length,Inet4Address.getByName(UdpTest.SERVER_HOST),(int) UdpTest.SERVER_PORT); //DatagramPacket datagramPacket = new DatagramPacket(data,data.length,Inet4Address.getByName(UdpTest.SERVER_HOST),3333); //DatagramPacket datagramPacket = new DatagramPacket(data,data.length); System.out.println("UdpClient: data initialized"); if (connect){ datagramSocket.connect(Inet4Address.getByName(UdpTest.SERVER_HOST),(int) UdpTest.SERVER_PORT); if (datagramSocket.isConnected()) System.out.println("UdpClient: datagramSocket connected"); } UdpTest.start = System.currentTimeMillis(); //for(int i=0; i<UdpTest.MSG_NUMBER; i++) { //System.out.println( "sending: " + i); //for(int j=0; j<data.length; j++) // System.out.print(datagramPacket.getData()[j]+", "); //System.out.println( ""); System.out.println("client: localport :"+datagramSocket.getLocalPort()); datagramSocket.send(datagramPacket); // le send System.out.println("client: localport :"+datagramSocket.getLocalPort()); if(datagramPacket.getLength() != UdpTest.MSG_SIZE) System.out.println(datagramPacket.getLength() + " != " +UdpTest.MSG_SIZE); UdpTest.total_sent ++; } datagramSocket.receive(datagramPacket); System.out.println("client: portsource paquet recu :"+ datagramPacket.getPort()); UdpTest.end = System.currentTimeMillis(); } catch(Exception e) { e.printStackTrace(); } }
Example 17
Source File: TelemetryService.java From AirMapSDK-Android with Apache License 2.0 | 4 votes |
private void connect() throws UnknownHostException, SocketException { InetAddress address = InetAddress.getByName(telemetryBaseUrl); socket = new DatagramSocket(); socket.connect(address, telemetryPort); }
Example 18
Source File: UdpSocketTest.java From pinpoint with Apache License 2.0 | 4 votes |
@Before public void setUp() throws SocketException { receiver = new DatagramSocket(PORT); sender = new DatagramSocket(); sender.connect(new InetSocketAddress("localhost", PORT)); }
Example 19
Source File: DiscoveryTest.java From freeacs with MIT License | 4 votes |
private void test3() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; do { try { // Test 3 including response DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); sendSocket.connect(InetAddress.getByName(stunServer), port); sendSocket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); changeRequest.setChangePort(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); sendSocket.send(send); LOGGER.debug("Test 3: Binding Request sent."); int localPort = sendSocket.getLocalPort(); InetAddress localAddress = sendSocket.getLocalAddress(); sendSocket.close(); DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort()); receiveSocket.setSoTimeout(timeout); MessageHeader receiveMH = new MessageHeader(); while (!receiveMH.equalTransactionID(sendMH)) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); receiveSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return; } if (nodeNatted) { di.setRestrictedCone(); LOGGER.debug("Node is behind a restricted NAT."); return; } } catch (SocketTimeoutException ste) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 3: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = timeSinceFirstTransmission * 2; if (timeoutAddValue > 1600) { timeoutAddValue = 1600; } timeout = timeoutAddValue; } else { LOGGER.debug( "Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); di.setPortRestrictedCone(); LOGGER.debug("Node is behind a port restricted NAT."); return; } } } while (true); }
Example 20
Source File: DiscoveryTest.java From freeacs with MIT License | 4 votes |
private boolean test2() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { int timeSinceFirstTransmission = 0; int timeout = timeoutInitValue; do { try { // Test 2 including response DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); sendSocket.connect(InetAddress.getByName(stunServer), port); sendSocket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); changeRequest.setChangeIP(); changeRequest.setChangePort(); sendMH.addMessageAttribute(changeRequest); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length); sendSocket.send(send); LOGGER.debug("Test 2: Binding Request sent."); int localPort = sendSocket.getLocalPort(); InetAddress localAddress = sendSocket.getLocalAddress(); sendSocket.close(); DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort()); receiveSocket.setSoTimeout(timeout); MessageHeader receiveMH = new MessageHeader(); while (!receiveMH.equalTransactionID(sendMH)) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); receiveSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { di.setError(ec.getResponseCode(), ec.getReason()); LOGGER.debug("Message header contains an Errorcode message attribute."); return false; } if (!nodeNatted) { di.setOpenAccess(); LOGGER.debug( "Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation)."); } else { di.setFullCone(); LOGGER.debug("Node is behind a full-cone NAT."); } return false; } catch (SocketTimeoutException ste) { if (timeSinceFirstTransmission < 7900) { LOGGER.debug("Test 2: Socket timeout while receiving the response."); timeSinceFirstTransmission += timeout; int timeoutAddValue = timeSinceFirstTransmission * 2; if (timeoutAddValue > 1600) { timeoutAddValue = 1600; } timeout = timeoutAddValue; } else { LOGGER.debug( "Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); if (!nodeNatted) { di.setSymmetricUDPFirewall(); LOGGER.debug("Node is behind a symmetric UDP firewall."); return false; } else { // not is natted // redo test 1 with address and port as offered in the changed-address message attribute return true; } } } } while (true); }