JAVA get public network IP address and intranet IP address method __java

Source: Internet
Author: User
Tags stringbuffer
Package sockettest;


Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.net.InetAddress;
Import Java.net.URL;
Import java.net.URLConnection;


public class Ipdemo {
public static void Main (string[] args) {
try {
String ip1 = Getmyip ();
System.out.println ("MyIP:" + ip1);
String ip2 = getmyiplocal ();
System.out.println ("Mylocalip:" + ip2);
catch (IOException E1) {
E1.printstacktrace ();
}
}

private static String Getmyip () throws IOException {
InputStream ins = null;
try {
URL url = new URL ("http://ip.cn");
URLConnection con = url.openconnection ();
INS = Con.getinputstream ();
InputStreamReader Isreader = new InputStreamReader (INS, "Utf-8");
BufferedReader breader = new BufferedReader (Isreader);
StringBuffer webcontent = new StringBuffer ();
String str = NULL;
while (str = Breader.readline ())!= null) {
Webcontent.append (str);
}
int start = Webcontent.indexof ("<code>") +6;
int end = Webcontent.indexof ("</code");
Return webcontent.substring (start, end);
finally {
if (ins!= null) {
Ins.close ();
}
}
}

private static String getmyiplocal () throws IOException {
InetAddress ia = Inetaddress.getlocalhost ();
return ia.gethostaddress ();
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.