获取本机IP地址信息

直接上代码

/**
 * 获取本地信息
 */
public interface LocalInfoGetService {
    LocalInfoWebDTO getLocalInfo();
}

package org.khm.ut.othertool.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.khm.ut.othertool.dto.LocalInfoWebDTO;
import org.khm.ut.othertool.service.LocalInfoGetService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
@Service
@Slf4j
@Transactional
public class LocalInfoGetServiceImpl implements LocalInfoGetService {
    @Override
    public LocalInfoWebDTO getLocalInfo() {
        LocalInfoWebDTO localInfoWebDTO = new LocalInfoWebDTO();
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
            localInfoWebDTO.setHostAddress(inetAddress.getHostAddress());// 本机ip
            localInfoWebDTO.setHostName(inetAddress.getHostName());// 本机用户名
            Element element = Jsoup.connect("http://www.ip38.com/").get()
                    .select("a[href^=/ip.php?ip]").first();
            if (element != null) {
                localInfoWebDTO.setIp(element.text());// 网络ip
            }
            URL url = new URL("http://opendata.baidu.com/api.php?query=" + localInfoWebDTO.getHostAddress() + "&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=utf-8&format=json");
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            JSONObject jsStr = JSON.parseObject(result.toString());
            JSONArray jsData = (JSONArray) jsStr.get("data");
            JSONObject data = (JSONObject) jsData.get(0);// 位置
            localInfoWebDTO.setIpAddress((String) data.get("location"));// ip所在地
            return localInfoWebDTO;
        } catch (Exception e) {
            return null;
        }
    }
}

你可能感兴趣的:(万能工具集,tcp/ip,chrome,网络协议,java)