public void listen() { while (true) { Socket clientSoc = null; try { clientSoc = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept Socket Error"); System.exit(1); } /* Send Welcome Message */ try { out = new PrintWriter(clientSoc.getOutputStream(), true); out.println("Thank you for connecting"); System.out.println("Connection successful with client " + clientSoc.getLocalAddress()); System.out.println("Waiting for input from " + clientSoc.getLocalAddress()); } catch (IOException e) { e.printStackTrace(); } new Thread(new ClientConnected(clientSoc, out)).start(); } }
/** @see com.thinkparity.network.NetworkConnection#connect() */ @Override public void connect() throws NetworkException { logger.logTraceId(); logger.logInfo("{0} - Connect.", getId()); Exception lastX = null; connected = false; for (final NetworkProxy proxy : proxies) { this.proxy = proxy; try { connectViaProxy(); setSocketOptions(); setSocketStreams(); logger.logInfo("{0} - Connected.", getId()); logger.logDebug( "{0} - Local: {1}:{2}", getId(), socket.getLocalAddress().getHostAddress(), socket.getLocalPort()); final InetSocketAddress remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); logger.logDebug( "{0} - Remote: {1}:{2}", getId(), remoteSocketAddress.getAddress().getHostAddress(), remoteSocketAddress.getPort()); connected = true; break; } catch (final SocketException sx) { lastX = sx; } catch (final IOException iox) { lastX = iox; } } if (false == connected) { throw new NetworkException(lastX); } }
@Test public void testSocketBind() throws Exception { final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); final int localPort = 8888; final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2}); final int remotePort = 80; final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort); final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort); Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress); Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress); Mockito.when(socket.getLocalAddress()).thenReturn(localAddress); Mockito.when(socket.getLocalPort()).thenReturn(localPort); Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress); Mockito.when(socket.getPort()).thenReturn(remotePort); conn.bind(socket); Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString()); Assert.assertTrue(conn.isOpen()); Assert.assertEquals(8888, conn.getLocalPort()); Assert.assertEquals(80, conn.getRemotePort()); Assert.assertEquals( InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), conn.getLocalAddress()); Assert.assertEquals( InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), conn.getRemoteAddress()); }
public InetAddress getLocalAddress() { if (isOpen()) { return mSocket.getLocalAddress(); } else { return null; } }
public static void printSocketParameters(Socket cl) throws SocketException { boolean SO_KEEPALIVE = cl.getKeepAlive(); boolean TCP_NODELAY = cl.getTcpNoDelay(); int SO_LINGER = cl.getSoLinger(); int SO_TIMEOUT = cl.getSoTimeout(); int SO_RCVBUF = cl.getReceiveBufferSize(); int SO_SNDBUF = cl.getSendBufferSize(); int trafficClassVal = cl.getTrafficClass(); /* 0 <= trafficClassVal <= 255 IPTOS_LOWCOST (0x02) IPTOS_RELIABILITY (0x04) IPTOS_THROUGHPUT (0x08) IPTOS_LOWDELAY (0x10) */ int remotePort = cl.getPort(); int localPort = cl.getLocalPort(); String localIP = getIPstr(cl.getLocalAddress()); String remoteIP = getIPstr(cl.getInetAddress()); System.out.println("Socket Paramaters :"); System.out.println("SO_KEEPAILVE = " + SO_KEEPALIVE + " TCP_NODELAY = " + TCP_NODELAY); System.out.println("SO_LINGER = " + SO_LINGER + " SO_TIMEOUT = " + SO_TIMEOUT); System.out.println("SO_RCVBUF = " + SO_RCVBUF + " SO_SNDBUF = " + SO_SNDBUF); System.out.println("Traffic Class = " + trafficClassVal); System.out.println("Local Address = " + localIP + ":" + localPort); System.out.println("Remote Address = " + remoteIP + ":" + remotePort); }
private void onConnect(final ProxyMessage msg) throws IOException { Socket s; if (proxy == null) { s = new Socket(msg.ip, msg.port); } else { s = new SocksSocket(proxy, msg.ip, msg.port); } log.info("Connected to " + s.getInetAddress() + ":" + s.getPort()); ProxyMessage response = null; final InetAddress localAddress = s.getLocalAddress(); final int localPort = s.getLocalPort(); if (msg instanceof Socks5Message) { final int cmd = SocksProxyBase.SOCKS_SUCCESS; Socks5Message socks5Message = new Socks5Message(cmd, localAddress, localPort); socks5Message.setDnsResolver(dnsResolver); response = socks5Message; } else { final int cmd = Socks4Message.REPLY_OK; Socks4Message socks4Message = new Socks4Message(cmd, localAddress, localPort); socks4Message.setDnsResolver(dnsResolver); response = socks4Message; } response.write(out); startPipe(s); }
@Override public DiscoveryResult createResult(ServiceInfo service) { if (service.getApplication().contains("mieleathome")) { ThingUID uid = getThingUID(service); if (uid != null) { Map<String, Object> properties = new HashMap<>(2); InetAddress[] addresses = service.getInetAddresses(); if (addresses.length > 0 && addresses[0] != null) { properties.put(MieleBindingConstants.HOST, addresses[0].getHostAddress()); Socket socket = null; try { socket = new Socket(addresses[0], 80); InetAddress ourAddress = socket.getLocalAddress(); properties.put(MieleBindingConstants.INTERFACE, ourAddress.getHostAddress()); } catch (IOException e) { logger.error( "An exception occurred while connecting to the Miele Gateway : '{}'", e.getMessage()); } } return DiscoveryResultBuilder.create(uid) .withProperties(properties) .withRepresentationProperty(uid.getId()) .withLabel("Miele XGW3000 Gateway") .build(); } } return null; }
public String toString() { StringBuilder ret = new StringBuilder(); InetAddress local = null, remote = null; String local_str, remote_str; Socket tmp_sock = sock; if (tmp_sock == null) ret.append("<null socket>"); else { // since the sock variable gets set to null we want to make // make sure we make it through here without a nullpointer exception local = tmp_sock.getLocalAddress(); remote = tmp_sock.getInetAddress(); local_str = local != null ? Util.shortName(local) : "<null>"; remote_str = remote != null ? Util.shortName(remote) : "<null>"; ret.append( '<' + local_str + ':' + tmp_sock.getLocalPort() + " --> " + remote_str + ':' + tmp_sock.getPort() + "> (" + ((System.currentTimeMillis() - last_access) / 1000) + " secs old)"); } tmp_sock = null; return ret.toString(); }
public void run() { try { try { scanner = new Scanner(socket.getInputStream()); out = new PrintWriter(socket.getOutputStream()); while (true) { checkConn(); if (!scanner.hasNext()) { return; } msg = scanner.nextLine(); System.out.println("Client said: " + msg); for (int i = 1; i <= Server.ConnectionArray.size(); i++) { Socket tSocket = (Socket) Server.ConnectionArray.get(i - 1); PrintWriter tOut = new PrintWriter(tSocket.getOutputStream()); tOut.println(msg); tOut.flush(); System.out.println("Sent to: " + tSocket.getLocalAddress().getHostName()); } } } finally { socket.close(); } } catch (IOException e) { e.printStackTrace(); } }
/** Setup the sockets needed for the given transfer mode (either passive or active). */ private void setupTransferMode() { String resp = ""; if (passive) { debug("Switching to passive mode"); System.out.println("=> PASV"); out.println(commands[PASV]); resp = getResponse(); System.out.println(resp); /* If we've successfully entered passive mode, setup the socket */ if (resp.startsWith("227")) { String[] foo = resp.split(","); int pasvPort = new Integer(foo[4]) * 256 + new Integer(foo[5].replaceAll("[a-zA-Z).]+", "")); debug("Opening passive socket on " + serverAddr + ":" + pasvPort); try { pasvSock = new Socket(serverAddr, pasvPort, null, sock.getLocalPort() + 1); pasvIn = new BufferedReader(new InputStreamReader(pasvSock.getInputStream())); } catch (IOException e) { System.err.println(e.getMessage()); } } else { debug("Got invalid response from PASV command"); } } else { /* Active mode */ debug("Switching to active mode"); try { activeSock = new ServerSocket(0); } catch (IOException e) { System.err.println("Error creating active socket: " + e.getMessage()); } byte[] addr = sock.getLocalAddress().getAddress(); debug("Listening on local port " + activeSock.getLocalPort()); String portCmd = "PORT " + ((int) addr[0] & 0xFF) + "," + ((int) addr[1] & 0xFF) + "," + ((int) addr[2] & 0xFF) + "," + ((int) addr[3] & 0xFF) + "," + activeSock.getLocalPort() / 256 + "," + activeSock.getLocalPort() % 256; System.out.println("=> " + portCmd); out.println(portCmd); System.out.println(getResponse()); } }
private void bindV4(InputStream in, OutputStream out, InetAddress baddr, int lport) throws IOException { if (!(baddr instanceof Inet4Address)) { throw new SocketException("SOCKS V4 requires IPv4 only addresses"); } super.bind(baddr, lport); byte[] addr1 = baddr.getAddress(); /* Test for AnyLocal */ InetAddress naddr = baddr; if (naddr.isAnyLocalAddress()) { naddr = cmdsock.getLocalAddress(); addr1 = naddr.getAddress(); } out.write(PROTO_VERS4); out.write(BIND); out.write((super.getLocalPort() >> 8) & 0xff); out.write((super.getLocalPort() >> 0) & 0xff); out.write(addr1); String userName = (String) java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("user.name")); try { out.write(userName.getBytes("ISO-8859-1")); } catch (java.io.UnsupportedEncodingException uee) { assert false; } out.write(0); out.flush(); byte[] data = new byte[8]; int n = readSocksReply(in, data); if (n != 8) throw new SocketException("Reply from SOCKS server has bad length: " + n); if (data[0] != 0 && data[0] != 4) throw new SocketException("Reply from SOCKS server has bad version"); SocketException ex = null; switch (data[1]) { case 90: // Success! external_address = new InetSocketAddress(baddr, lport); break; case 91: ex = new SocketException("SOCKS request rejected"); break; case 92: ex = new SocketException("SOCKS server couldn't reach destination"); break; case 93: ex = new SocketException("SOCKS authentication failed"); break; default: ex = new SocketException("Reply from SOCKS server contains bad status"); break; } if (ex != null) { in.close(); out.close(); throw ex; } }
private String describeConnection(Socket s) { return String.format( "from %s:%d to %s:%d", s.getInetAddress().getHostAddress(), s.getPort(), s.getLocalAddress().getHostAddress(), s.getLocalPort()); }
private static String localIp(String cloudControllerUri) { final URI uri = URI.create(cloudControllerUri); final int port = uri.getPort() == -1 ? 80 : uri.getPort(); try (Socket socket = new Socket(uri.getHost(), port)) { return socket.getLocalAddress().getHostAddress(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Create a new message and record the source ip and port * * @param aSocket The socket through which the message will be read. * @return The {@link AS2Message} to use and never <code>null</code>. */ @Nonnull protected AS2Message createMessage(@Nonnull final Socket aSocket) { final AS2Message aMsg = new AS2Message(); aMsg.setAttribute(CNetAttribute.MA_SOURCE_IP, aSocket.getInetAddress().toString()); aMsg.setAttribute(CNetAttribute.MA_SOURCE_PORT, Integer.toString(aSocket.getPort())); aMsg.setAttribute(CNetAttribute.MA_DESTINATION_IP, aSocket.getLocalAddress().toString()); aMsg.setAttribute(CNetAttribute.MA_DESTINATION_PORT, Integer.toString(aSocket.getLocalPort())); aMsg.setAttribute(AS2Message.ATTRIBUTE_RECEIVED, Boolean.TRUE.toString()); return aMsg; }
private String getSockAddress() { StringBuilder sb = new StringBuilder(); if (sock != null) { sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort()); sb.append(" - ") .append(sock.getInetAddress().getHostAddress()) .append(':') .append(sock.getPort()); } return sb.toString(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } username = (EditText) findViewById(R.id.loginName); login = (Button) findViewById(R.id.login); try { boolean connect = false; while (!connect) { msocket = new Socket(serverIP, serverPort); System.out.println("connect succeed!"); clientName = msocket.getLocalAddress().toString(); clientName = clientName.substring(1); input = new DataInputStream(msocket.getInputStream()); output = new DataOutputStream(msocket.getOutputStream()); stdIn = new BufferedReader(new InputStreamReader(System.in)); String sayHello = ""; sayHello += "MINET "; sayHello += clientName; sayHello += "\r\n"; output.writeUTF(sayHello); String hello; hello = input.readUTF(); if (Hello(hello)) { connect = true; Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show(); } } login.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { // TODO 自动生成的方法存根 Login(); } }); } catch (UnknownHostException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }
private void port() throws IOException { write( "PORT " //$NON-NLS-1$ + controlSocket.getLocalAddress().getHostAddress().replace('.', ',') + ',' + (dataPort >> 8) + ',' + (dataPort & 255) + "\r\n"); //$NON-NLS-1$ if (getReply() != FTP_OK) { throw new IOException(Msg.getString("K0099")); // $NON-NLS-1$ } }
public static String getLocalIP() { String ipAddrStr = ""; try { Socket s = new Socket("www.google.com", 80); // any site at all InetAddress ip = s.getLocalAddress(); ipAddrStr = ip.getHostAddress(); s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ipAddrStr; }
public synchronized void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { Socket socket = ((ModifiedHttpContext) context).getSocket(); // Parse URI and configure the Session accordingly final String uri = URLDecoder.decode(request.getRequestLine().getUri()); final String sessionDescriptor = "v=0\r\n" + "o=- 15143872582342435176 15143872582342435176 IN IP4 " + socket.getLocalAddress().getHostName() + "\r\n" + "s=Unnamed\r\n" + "i=N/A\r\n" + "c=IN IP4 " + socket.getLocalAddress().getHostAddress() + "\r\n" + "t=0 0\r\n" + "a=tool:spydroid\r\n" + "a=recvonly\r\n" + "a=type:broadcast\r\n" + "a=charset:UTF-8\r\n"; response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate( new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(sessionDescriptor); writer.flush(); } }); body.setContentType("text/plain; charset=UTF-8"); response.setEntity(body); }
public String toString() { Socket tmp_sock = sock; if (tmp_sock == null) return "<null socket>"; InetAddress local = tmp_sock.getLocalAddress(), remote = tmp_sock.getInetAddress(); String local_str = local != null ? Util.shortName(local) : "<null>"; String remote_str = remote != null ? Util.shortName(remote) : "<null>"; return String.format( "%s:%s --> %s:%s (%d secs old) [%s] [recv_buf=%d]", local_str, tmp_sock.getLocalPort(), remote_str, tmp_sock.getPort(), TimeUnit.SECONDS.convert(getTimestamp() - last_access, TimeUnit.NANOSECONDS), status(), receiver != null ? receiver.bufferSize() : 0); }
@Override public Ice.ConnectionInfo getInfo() { Ice.TCPConnectionInfo info = new Ice.TCPConnectionInfo(); if (_stream.fd() != null) { java.net.Socket socket = _stream.fd().socket(); info.localAddress = socket.getLocalAddress().getHostAddress(); info.localPort = socket.getLocalPort(); if (socket.getInetAddress() != null) { info.remoteAddress = socket.getInetAddress().getHostAddress(); info.remotePort = socket.getPort(); } if (!socket.isClosed()) { info.rcvSize = Network.getRecvBufferSize(_stream.fd()); info.sndSize = Network.getSendBufferSize(_stream.fd()); } } return info; }
public void checkConn() { try { if (!socket.isConnected()) { for (int i = 1; i <= Server.ConnectionArray.size(); i++) { if (Server.ConnectionArray.get(i) == socket) { Server.ConnectionArray.remove(i); } } for (int i = 1; i <= Server.ConnectionArray.size(); i++) { Socket tSocket = (Socket) Server.ConnectionArray.get(i - 1); PrintWriter tOut = new PrintWriter(tSocket.getOutputStream()); tOut.println(tSocket.getLocalAddress().getHostName() + " disconnected!"); } } } catch (IOException e) { e.printStackTrace(); } }
public static InetAddress getMyIP(String host, int port) throws IOException, UnknownHostException { InetAddress inetAddress = InetAddress.getByName(host); InetAddress listenAddress; if (inetAddress.isLoopbackAddress()) { listenAddress = inetAddress; } else { Socket testSocket = new Socket(host, port); listenAddress = testSocket.getLocalAddress(); testSocket.close(); /* * At first the following code looks like a better solution, however * InetAddress.isReachable does not work without being a super user. */ // // Find first local address the master host is reachable from // final Enumeration<NetworkInterface> networkInterfaces = // NetworkInterface.getNetworkInterfaces(); // // while(networkInterfaces.hasMoreElements()) { // NetworkInterface iface = networkInterfaces.nextElement(); // // if(iface.isLoopback()) // { // continue; // } // // if(inetAddress.isReachable(iface, 0, 100)) // { // for(InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) // { // if(ifaceAddr.getAddress().getAddress().length == 4) // { // listenAddress = ifaceAddr.getAddress(); // } // } // } // } } return listenAddress; }
public static void main(String[] args) { try { Socket s = new Socket("www.google.com", 80); try { InetAddress remote = s.getInetAddress(); System.out.println("Remote host " + remote.getHostName()); System.out.println("Remote IP " + remote.getHostAddress()); System.out.println("Remote port " + s.getPort()); InetAddress local = s.getLocalAddress(); System.out.println("Local host " + local.getHostName()); System.out.println("Local IP " + local.getHostAddress()); System.out.println("Local port " + s.getLocalPort()); } finally { s.close(); } } catch (IOException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") private void los() { JFrame frame = new JFrame("Server"); log = new JTextArea(20, 30); log.setLineWrap(true); log.setWrapStyleWord(true); log.setEditable(false); JScrollPane scr = new JScrollPane(log); scr.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); frame.add(scr); frame.setSize(300, 300); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); clientAusgabeStröme = new ArrayList(); try { ServerSocket serverSock = new ServerSocket(5000); log.append("Server gestaret\n"); while (true) { Socket clientSocket = serverSock.accept(); PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); clientAusgabeStröme.add(writer); Thread t = new Thread(new ClientHandler(clientSocket)); t.start(); log.append("Habe eine Verbindung von " + clientSocket.getLocalAddress() + "\n"); } } catch (Exception ex) { ex.printStackTrace(); } }
public static void main(String[] args) throws IOException { try { final int PORT = 444; ServerSocket SERVER = new ServerSocket(PORT); System.out.println("Waiting for clients..."); while (true) { Socket SOCK = SERVER.accept(); ConnectionArray.add(SOCK); System.out.println("Client connected from: " + SOCK.getLocalAddress().getHostName()); AddUserName(SOCK); A_Chat_Server_Return CHAT = new A_Chat_Server_Return(SOCK); Thread X = new Thread(CHAT); X.start(); } } catch (Exception e) { System.out.println(e); } }
public void run() { try { ServerSocket serverSocket = new ServerSocket(7497); // infinite loop to wait for connections while (true) { log.info("Server waiting for Clients on port " + 7497); Socket socket = serverSocket.accept(); // accept connection log.info( " Connection Received from " + socket.getInetAddress() + " on port " + socket.getPort() + " to port " + socket.getLocalPort() + " of " + socket.getLocalAddress()); sInput = new DataInputStream(socket.getInputStream()); sOutput = new DataOutputStream(socket.getOutputStream()); MessageSender.instance.setup(sOutput); ClientThread t = new ClientThread(sInput); t.start(); // int version = sInput.read(); // log.info(version); write("76".getBytes()); // Send Server Id write("Test Time".getBytes()); // Send Test Time // int ClientId = sInput.read(); //Client Id // log.info(ClientId); } } catch (Exception e) { log.warn(e); } }
public InetSocketAddress getLocalAddress() { Socket s = connection.getChannel().socket(); InetAddress ia = s.getLocalAddress(); int port = s.getLocalPort(); return new InetSocketAddress(ia, port); }
@Override public InetAddress getLocalAddress() { return sock.getLocalAddress(); }
public void alert() { System.out.println("\n !!!!!!! tcpclient.!!!!!!!!!! \n"); String saddr; int ch; String login_id = " "; try { Socket clientSocket = new Socket("192.168.0.5", 6789); // 172.0.0.1 /* * FileReader file_uid_read=null; * * * * * file_uid_read=new FileReader("store_uid.txt"); Character c; * * while((ch=file_uid_read.read())!=-1) { c=new Character((char)ch); * login_id=login_id+c.toString(); System.out.println( * "login id isssss"+login_id); * * }//while * * */ String sentence; System.out.println("chkpt 1"); String modifiedSentence; // BufferedReader inFromUser = new BufferedReader( new // InputStreamReader(System.in)); System.out.println("chkpt 1"); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); // BufferedReader inFromServer = new BufferedReader(new // InputStreamReader(clientSocket.getInputStream())); // sentence = inFromUser.readLine(); System.out.println("chkpt 1"); // calc ip addr // InetAddress addr=InetAddress.getLocalHost(); saddr = passusername + " INVALID LOGIN ATTEMPT AT: ip address " + (clientSocket.getLocalAddress()).toString(); System.out.println("adddrrrr" + saddr); saddr = saddr + " by user name " + passusername; outToServer.writeBytes(saddr); // modifiedSentence = inFromServer.readLine(); // System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } // try catch (Exception e) { System.out.println("2EXCEPTION"); } }