后台是一个C++程序,进行了一个ip地址的转换,前台需要用Java进行转换,哪位指点一下?

解决方案 »

  1.   

    inet_toa();是将一个ipv4的地址转化为字符串,
    java中对应的有:InetAddress getByAddress(byte[] addr) ;
      

  2.   

    是这样,数据库中存在一个数值型字段,存放把类似一个数值,需要通过java把该数值转换为实际的IP地址。
    数据库中的数值,是通过C++ inet_ntoa()转换的。同样,我也需要通过java将一个正常的ip地址转换为一个数值,共后台的c++程序反向解析
      

  3.   

    由于java中没有无符号数, 所以用int操作起来很麻烦, 不如用4个byte来操作还有就是lz用java和c++和用的时候, 要注意字节的顺序
    public static byte[] inet_addr(String ipstr) {
    try {
    InetAddress ia = InetAddress.getByName(ipstr);
    byte[] iparr = ia.getAddress();

    return iparr;
    }
    catch (UnknownHostException uhe) {
    uhe.printStackTrace();
    return null;
    }
    }

    public static String inet_toa(byte[] iparr) {
    try {
    InetAddress ia = InetAddress.getByAddress(iparr);
    String ipstr = ia.getHostAddress();

    return ipstr;
    }
    catch (UnknownHostException uhe) {
    uhe.printStackTrace();
    return null;
    }
    }
      

  4.   

    汇集大家的思路,弄了个全的,请大家参考:
    import java.net.InetAddress;
    import java.net.UnknownHostException;/**
     * 192.168.0.18 -1062731758
     */
    public class TestIPNum { public static void main(String[] args) throws UnknownHostException { String host = TestIPNum.inet_toa(-1062731758);
    System.out.println(host); System.out.println(TestIPNum
    .inet_addr("192.168.0.18"));

    System.out.println(Integer.MAX_VALUE);
    System.out.println(Integer.MIN_VALUE);
    } public static int inet_addr(String ipstr) {
    try {
    InetAddress ia = InetAddress.getByName(ipstr);
    byte[] iparr = ia.getAddress(); int iRet = byte2Int(iparr);
    return iRet;
    } catch (UnknownHostException uhe) {
    uhe.printStackTrace();
    return 0;
    }
    } public static String inet_toa(int ipInt) {
    try {
    byte[] iparr = int2Byte(ipInt);
    InetAddress ia = InetAddress.getByAddress(iparr);
    String ipstr = ia.getHostAddress(); return ipstr;
    } catch (UnknownHostException uhe) {
    uhe.printStackTrace();
    return null;
    }
    } public static byte[] int2Byte(int intValue) {
    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
    b[i] = (byte) (intValue >> 8 * (3 - i) & 0xFF);
    }
    return b;
    } public static int byte2Int(byte[] b) {
    int intValue = 0;
    for (int i = 0; i < b.length; i++) {
    intValue += (b[i] & 0xFF) << (8 * (3 - i));
    }
    return intValue;
    }}