/** * Constructor. Creates a datagram send socket and connects it to the Ganglia hypertable extension * listen port. Initializes mPrefix to "ht." + <code>component</code> + ".". * * @param component Hypertable component ("fsbroker", "hyperspace, "master", "rangeserver", or * "thriftbroker") * @param props Configuration properties */ public MetricsCollectorGanglia(String component, Properties props) { mPrefix = "ht." + component + "."; String str = props.getProperty("Hypertable.Metrics.Ganglia.Port", "15860"); mPort = Integer.parseInt(str); str = props.getProperty("Hypertable.Metrics.Ganglia.Disabled"); if (str != null && str.equalsIgnoreCase("true")) mDisabled = true; try { mAddr = InetAddress.getByName("localhost"); } catch (UnknownHostException e) { System.out.println("UnknownHostException : 'localhost'"); e.printStackTrace(); System.exit(-1); } try { mSocket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); System.exit(-1); } mSocket.connect(mAddr, mPort); mConnected = true; }
public static String FindIP() { Enumeration<NetworkInterface> interfaces = null; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); } while (interfaces.hasMoreElements()) { NetworkInterface ifc = interfaces.nextElement(); if (ifc.getName().equals("ppp" + myDigit)) { try { if (ifc.isUp()) { List<InterfaceAddress> ia = ifc.getInterfaceAddresses(); System.out.println("IFC ip" + ia.get(0).getAddress().toString()); return ia.get(0).getAddress().toString(); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; }
void empty() { try { rtp_socket.getDatagramSocket().setSoTimeout(1); for (; ; ) rtp_socket.receive(rtp_packet); } catch (SocketException e2) { if (!Sipdroid.release) e2.printStackTrace(); } catch (IOException e) { } try { rtp_socket.getDatagramSocket().setSoTimeout(SO_TIMEOUT); } catch (SocketException e2) { if (!Sipdroid.release) e2.printStackTrace(); } seq = 0; }
/** Initializes the context. */ public void init(String contextName, String serverSpecList) { String periodStr = getAttribute(PERIOD_PROPERTY); if (periodStr != null) { int period = 0; try { period = Integer.parseInt(periodStr); } catch (NumberFormatException nfe) { } if (period <= 0) { throw new AnalyticsException("Invalid period: " + periodStr); } setPeriod(period); } metricsServers_ = parse(serverSpecList, port_); unitsTable_ = getAttributeTable(UNITS_PROPERTY); slopeTable_ = getAttributeTable(SLOPE_PROPERTY); tmaxTable_ = getAttributeTable(TMAX_PROPERTY); dmaxTable_ = getAttributeTable(DMAX_PROPERTY); try { datagramSocket_ = new DatagramSocket(); } catch (SocketException se) { se.printStackTrace(); } }
private Core() { boolean f = false; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = (NetworkInterface) en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { String ipAddress = inetAddress.getHostAddress().toString(); this.ip = inetAddress; f = true; break; } } if (f) break; } } catch (SocketException ex) { ex.printStackTrace(); System.exit(1); } this.teams = new HashMap<String, Team>(); this.judges = new HashMap<String, Judge>(); this.problems = new HashMap<String, ProblemInfo>(); this.scheduler = new Scheduler(); this.timer = new ContestTimer(300 * 60); try { readConfigure(); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort); }
/** * This method created a socket and a packet. It is performed only once in * * <p>the constructor of JoyActivity. * * <p>Indeed, two objects are required for UDP communication, a socket and a * * <p>packet as respective class DatagramSocket and DatagramPacket (classes * * <p>available in the Android libraries). * * @param ComandeUDP start command * @param port The Port to use * @param host The Address IP target */ public DatagramSocket CreationSocketPacket(String ComandeUDP, int port, String host) { buffer = new byte[512]; try { // TRY CREATION SOCKET udp_socket = new DatagramSocket(); } catch (SocketException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { // INSERTION TRAME buffer = ComandeUDP.concat("\r").getBytes("ASCII"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // INSERTION ADRESSE adresse = InetAddress.getByName(host); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } udp_packet = new DatagramPacket(buffer, buffer.length, adresse, port); return udp_socket; }
@Override protected Void doInBackground(Void... params) { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface thisInterface = networkInterfaces.nextElement(); Enumeration<InetAddress> inetAddresses = thisInterface.getInetAddresses(); if (inetAddresses.hasMoreElements()) { String niInfo = thisInterface.getDisplayName() + "\n"; while (inetAddresses.hasMoreElements()) { InetAddress thisAddress = inetAddresses.nextElement(); niInfo += "---\n"; niInfo += "Address: " + thisAddress.getAddress() + "\n"; niInfo += "CanonicalHostName: " + thisAddress.getCanonicalHostName() + "\n"; niInfo += "HostAddress: " + thisAddress.getHostAddress() + "\n"; niInfo += "HostName: " + thisAddress.getHostName() + "\n"; } publishProgress(niInfo); } } } catch (SocketException e) { e.printStackTrace(); } return null; }
/** * 获取本地Ip地址 * * @param context * @return */ public static String getLocalIpAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null && wifiInfo.getIpAddress() != 0) { return android.text.format.Formatter.formatIpAddress(wifiInfo.getIpAddress()); } else { try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface intf = en.nextElement(); Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); while (enumIpAddr.hasMoreElements()) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().indexOf(":") == -1) { String ipAddress = inetAddress.getHostAddress(); if (!TextUtils.isEmpty(ipAddress) && !ipAddress.contains(":")) { return ipAddress; } } } } } catch (SocketException e) { e.printStackTrace(); } } return null; }
public void sendToClient(byte[] buffer, String ip) { String[] strings = ip.split(":"); try { DatagramPacket packet = new DatagramPacket( buffer, buffer.length, new InetSocketAddress(strings[0], Integer.parseInt(strings[1]))); if (PearCtrl.localUrl.contains(strings[0])) { socket.send(packet); } else { Burrow burrow = new Burrow(socket, packet); hashMap.put(ip, burrow); } } catch (SocketException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
public static void main(String argv[]) throws Exception { ServerSocket serverSocket = new ServerSocket(3333); Runtime.getRuntime() .addShutdownHook( new Thread() { public void run() { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }); try { Socket connectionSocket = serverSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while (true) { System.out.println(inFromClient.readLine()); } } catch (SocketException se) { System.out.println("Socket error"); se.printStackTrace(); } }
public static String getLocalIpAddress2() { String networkIp = null; try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface iface : interfaces) { if (iface.getDisplayName().equals("eth0")) { List<InetAddress> addresses = Collections.list(iface.getInetAddresses()); for (InetAddress address : addresses) { if (address instanceof Inet4Address) { networkIp = address.getHostAddress(); } } } else if (iface.getDisplayName().equals("wlan0")) { List<InetAddress> addresses = Collections.list(iface.getInetAddresses()); for (InetAddress address : addresses) { if (address instanceof Inet4Address) { networkIp = address.getHostAddress(); } } } } } catch (SocketException e) { e.printStackTrace(); } return networkIp; }
private void run() throws UnknownHostException { while (true) { try { serverSocket = new DatagramSocket(new Random().nextInt(1000) + 8000); break; } catch (SocketException e) { e.printStackTrace(); } } portListener = new PortListener(); portListener.start(); periodicConnectionCheck = new PeriodicConnectionCheck(); periodicConnectionCheck.start(); parent = new JFrame("Chat"); parent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); parent.setMinimumSize(new Dimension(300, 400)); parent.setLocationRelativeTo(null); this.gui = new GUI(); parent.getContentPane().add(this.gui, BorderLayout.CENTER); parent.pack(); parent.setVisible(true); showLoginDialog(); while (parent.isVisible()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
private static LinkedList<InetAddress> getNetworkAddresses() { final LinkedList<InetAddress> addrList = new LinkedList<InetAddress>(); try { final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { final NetworkInterface ni = nis.nextElement(); if (!ni.isLoopback()) { final Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { final InetAddress addr = addresses.nextElement(); if (!addr.isLoopbackAddress() && addr instanceof Inet4Address) { addrList.add(addr); } } } } } catch (final SocketException e) { e.printStackTrace(); } return addrList; }
public static void main(String[] args) { InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); System.out.print("Current MAC address : "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } System.out.println(sb.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } }
/** * Sets the 'java.rmi.server.hostname' system property. <br> * WARNING: Call it before creating rmi registry else it is of no use. </br> */ private void setRmiRegistryIpAddress() { StringBuilder bf = new StringBuilder(); try { NetworkInterface iface; for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { iface = (NetworkInterface) ifaces.nextElement(); InetAddress ia; Enumeration ips = iface.getInetAddresses(); while (ips.hasMoreElements()) { ia = (InetAddress) ips.nextElement(); // get all the ip aliases from all the network cards except for // loopback addresses. loop back addresses are not included because, then rmi registry // would // export objects on 127.0.0.1 or localhost => hence server would be accessible to clients // present only on localhost i.e the same machine as server!!!! if (ia instanceof Inet4Address && !ia.isLoopbackAddress()) { String ip = ia.getHostAddress(); bf.append(ip); bf.append(','); } } } String hosts = bf.toString(); if (hosts.endsWith(",")) // hosts="a,b,c," hosts = hosts.substring(0, hosts.lastIndexOf(",")); // hosts="a,b,c" // Note: if network card is disabled=>hosts is empty, rmi runtimes uses localhost/127.0.0.1. System.setProperty("java.rmi.server.hostname", hosts); } catch (SocketException e) { e.printStackTrace(); } }
/** * Name: getIPAddress Description: Iterates through the device's IPAddresses and returns first * non-local IPAddress * * @return String containing the first non-local IPAddress of the device. */ public InetAddress getIPAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface networkInterface = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { return inetAddress; } } } return InetAddress.getByName("127.0.0.1"); } catch (SocketException ex) { ex.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return null; }
public static String getLocalAddress() { try { // 遍历网卡,查找一个非回路ip地址并返回 Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); InetAddress ipv6Address = null; while (enumeration.hasMoreElements()) { final NetworkInterface networkInterface = enumeration.nextElement(); final Enumeration<InetAddress> en = networkInterface.getInetAddresses(); while (en.hasMoreElements()) { final InetAddress address = en.nextElement(); if (!address.isLoopbackAddress()) { if (address instanceof Inet6Address) { ipv6Address = address; } else { // 优先使用ipv4 return normalizeHostAddress(address); } } } } // 没有ipv4,再使用ipv6 if (ipv6Address != null) { return normalizeHostAddress(ipv6Address); } final InetAddress localHost = InetAddress.getLocalHost(); return normalizeHostAddress(localHost); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return null; }
public void init() { try { localAddress = InetAddress.getLocalHost(); if (localAddress.isLoopbackAddress()) { System.out.println("get local ip error!"); return; } NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress); List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses(); for (InterfaceAddress address : addresses) { if (address.getAddress() instanceof Inet6Address) { continue; } if (address.getBroadcast() != null) { broadcastAddress = address.getBroadcast(); break; } else { System.out.println("get broadcast address error!"); } } System.out.println("local ip address is " + localAddress.getHostAddress()); System.out.println("broadcast address is " + broadcastAddress.getHostAddress()); socket = new DatagramSocket(2000); socket.setBroadcast(true); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (SocketException se) { se.printStackTrace(); } }
static { try { mClient = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } }
// on linux system public void init2() { try { NetworkInterface networkInterface = NetworkInterface.getByName("eth0"); Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = inetAddresses.nextElement(); if (!address.isLinkLocalAddress()) { // just get IPv4 address localAddress = address; } } // get broadcast address List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses(); for (InterfaceAddress address : addresses) { if (address.getBroadcast() != null) { broadcastAddress = address.getBroadcast(); break; } } if (broadcastAddress == null) { System.out.println("get broadcast address error!"); } System.out.println("local ip address is " + localAddress.getHostAddress()); System.out.println("broadcast address is " + broadcastAddress.getHostAddress()); socket = new DatagramSocket(); socket.setBroadcast(true); } catch (SocketException se) { se.printStackTrace(); } }
public void setSoTimeout(int timeout) { try { _socket.setSoTimeout(timeout); } catch (SocketException e) { e.printStackTrace(); } }
public static void main(String[] argu) { try { new PureDNSListener().run(); } catch (SocketException e) { e.printStackTrace(); } }
private static String getNetworkInterface() { String networkInterfaceName = ">>>> modify networkInterface in us.codecraft.webmagic.utils.ProxyUtils"; Enumeration<NetworkInterface> enumeration = null; try { enumeration = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e1) { e1.printStackTrace(); } while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); Enumeration<InetAddress> addr = networkInterface.getInetAddresses(); while (addr.hasMoreElements()) { String s = addr.nextElement().getHostAddress(); Pattern IPV4_PATTERN = Pattern.compile( "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); if (s != null && IPV4_PATTERN.matcher(s).matches()) { networkInterfaceName += networkInterface.toString() + "IP:" + s + "\n\n"; } } } return networkInterfaceName; }
public static void main(String[] args) { if (args.length == 0) { System.err.println("Usage: ntp.NTPClient <hostname-or-address-list>"); System.exit(1); } NTPUDPClient client = new NTPUDPClient(); // We want to timeout if a response takes longer than 10 seconds client.setDefaultTimeout(10000); try { client.open(); for (String arg : args) { System.out.println(); try { InetAddress hostAddr = InetAddress.getByName(arg); System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); TimeInfo info = client.getTime(hostAddr); processResponse(info); } catch (IOException ioe) { ioe.printStackTrace(); } } } catch (SocketException e) { e.printStackTrace(); } client.close(); }
public void run() { while (!isThreadRunning) { byte[] ack_byte = new byte[2]; DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length); try { socketAck.setSoTimeout(5); } catch (SocketException e) { e.printStackTrace(); } try { socketAck.receive(packet_ack); } catch (IOException e) { e.printStackTrace(); } byte[] ackData = packet_ack.getData(); int packet_ack_num = getAckPaket(ackData); num_acked = Math.max(num_acked, packet_ack_num); Thread.yield(); } socketAck.close(); }
public DroneSocketClient(String serverAddress, int clientPort, int serverPort, int pingPort) throws DroneSocketClientException { this.serverAddress = serverAddress; this.clientPort = clientPort; this.pingPort = pingPort; this.serverPort = serverPort; try { srvAddr = InetAddress.getByName(serverAddress); } catch (UnknownHostException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "ERROR: UNKNOWN HOST!"); throw new DroneSocketClientException(""); } } try { clientSocket = new DatagramSocket(clientPort); clientSocket.setSoTimeout(packetTIMEOUT); } catch (SocketException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "CLIENTSOCKET BIND ERROR!"); throw new DroneSocketClientException(""); } } inData = new byte[1024]; outData = new byte[1024]; outPacket = new DatagramPacket(outData, outData.length, srvAddr, serverPort); inPacket = new DatagramPacket(inData, inData.length); }
public void run() { System.out.println("ExeUDPServer开始监听..." + UDP_PORT); DatagramSocket ds = null; try { ds = new DatagramSocket(UDP_PORT); } catch (BindException e) { System.out.println("UDP端口使用中...请重关闭程序启服务器"); } catch (SocketException e) { e.printStackTrace(); } while (ds != null) { DatagramPacket dp = new DatagramPacket(buf, buf.length); try { ds.receive(dp); // 得到把该数据包发来的端口和Ip int rport = dp.getPort(); InetAddress addr = dp.getAddress(); String recvStr = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server receive:" + recvStr + " from " + addr + " " + rport); // 给客户端回应 String sendStr = "echo of " + recvStr; byte[] sendBuf; sendBuf = sendStr.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport); ds.send(sendPacket); } catch (IOException e) { e.printStackTrace(); } } }
public void send(DatagramSocket ds, String IP, int port) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); try { dos.writeInt(msgType); // 消息类型 dos.writeUTF(id); // 用户id dos.writeUTF(name); // 用户名 dos.writeUTF(token); // 用户名 } catch (IOException e1) { e1.printStackTrace(); } byte[] buffer = baos.toByteArray(); try { DatagramPacket dp = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(IP, port)); ds.send(dp); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void run() { Log.d(TAG, "Starting keep alive..."); DatagramSocket socket = null; try { socket = new DatagramSocket(PORT); try { InetAddress host = InetAddress.getByName(mAddress); while (mTransmit) { byte[] buffer = {0x66}; DatagramPacket out = new DatagramPacket(buffer, buffer.length, host, PORT); socket.send(out); sleep(mInterval); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (SocketException e) { e.printStackTrace(); } finally { if (socket != null) { socket.close(); } } }
public void startServer() { try { serverSocket = MyUtil.getSocket(); log.info(MyUtil.getMyIPAddress()); log.info(MyUtil.getPort()); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while (true) { log.info("RPCServer.main() Running"); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); log.info( "============================================Packet Received from :" + IPAddress.getHostAddress()); log.info("=============================================Packet Recieved from Port:" + port); sendData = proccessRequest(receiveData); log.info( "=============================================Sending Response :" + new String(sendData)); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }