473,748 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to get a raw IP-addr into byte-array?

Java's InetAddress class has some methods that use
a byte-array to hold what it describes as a 'raw IP address'.

So, I assume that they mean an array like:
byte[] ba = new byte[4];
would hold an IPv4 address.

Ok, yes, in theory, there are enough bits to hold the values.
But, my Java book clearly states that a byte is a SIGNED
quantity, is part of the Integer class, and can hold values ranging from 127
to -128.
And, my book also states that there is no 'unsigned' keyword in Java.

So, given that, how would I write code to fill each of the 4 array
elements, when I have values as large as 255 (and never any negative
values)?

Let's say I want to StringToken-ize an IP-address from a string, to load
up a byte-array with the 4 values.
I have a string (IP-address) like:
192.168.0.1
I parse out the first value (192), but when I use code like:

String str = "192";
Integer i = Integer.getInte ger(str);
byte b = i.byteValue(); //Causes NullPointerExce ption

So, what extra hoop do I need to leap thru to get each octet into
its byte? (It probably should be obvious, but not to me.)

TIA...

Dave


Jul 17 '05 #1
2 26913
I'm not 100% sure why you need to do this. You can pass an IP address
as-is to the InetAddress.get ByName() method. You don't HAVE to give it a
DNS name.

That said, if you really still want to go down this road, I did create a
simple utility class which does bitwise casting between Integers and Bytes:

/*
* BitwiseCast.jav a
*
* Created on May 11, 2002, 9:21 PM
*/

package com.webcorp.uti l;

/** This class provides methods to casting values. For example, if we
* were attemptin to cast a byte of 0xFF, the number would be a NEGATIVE
* integer, which is incorrect. The integer should just be 255.
*
* @author Nathan Crause
* @version
*/
public class BitwiseCast {
public static int byte2int(byte b) {
int ret = 0;
byte work = b;

for (int i = 0; i < 8; ++i) {
ret <<= 1;
if ((work & 0x80) > 0) ret |= 0x01;
work <<= 1;
}

return ret;
}

public static byte int2byte(int b) {
byte ret = 0;
int work = b;

for (int i = 0; i < 8; ++i) {
ret <<= 1;
if ((work & 0x80) > 0) ret |= 0x01;
work <<= 1;
}

return ret;
}

public static void main(String args[]) {
int x = 200;
byte y = -100;
System.out.prin tln(x + "=" + int2byte(x));
System.out.prin tln(y + "=" + byte2int(y));
}
}

I hope this helps.


David Cook wrote:
Java's InetAddress class has some methods that use
a byte-array to hold what it describes as a 'raw IP address'.

So, I assume that they mean an array like:
byte[] ba = new byte[4];
would hold an IPv4 address.

Ok, yes, in theory, there are enough bits to hold the values.
But, my Java book clearly states that a byte is a SIGNED
quantity, is part of the Integer class, and can hold values ranging from 127
to -128.
And, my book also states that there is no 'unsigned' keyword in Java.

So, given that, how would I write code to fill each of the 4 array
elements, when I have values as large as 255 (and never any negative
values)?

Let's say I want to StringToken-ize an IP-address from a string, to load
up a byte-array with the 4 values.
I have a string (IP-address) like:
192.168.0.1
I parse out the first value (192), but when I use code like:

String str = "192";
Integer i = Integer.getInte ger(str);
byte b = i.byteValue(); //Causes NullPointerExce ption

So, what extra hoop do I need to leap thru to get each octet into
its byte? (It probably should be obvious, but not to me.)

TIA...

Dave

Jul 17 '05 #2
Well, say you had the address java.sun.com [209.249.116.143]. You
could pack that into a byte array thus:

byte[] addr = new byte[4];
addr[0] = (byte)209;
addr[1] = (byte)249;
addr[2] = (byte)116;
addr[3] = (byte)143;

Or you could just cram it all into an int, like so:

int addy = 209*16777216 + 249*65536 + 116*256 + 143;
System.out.prin tln("java.sun.c om = " + addy);

That prints out -772180849. But my browser doesn't like the sign, so
I need it unsigned:

System.out.prin tln("java.sun.c om = " +
((long)addy & 0xffffffffL));

That prints out 3522786447, and indeed, if I point my browser at

http://3522786447

it does the right thing. Hey there, Gosling! We need unsigned!
BTW, Integer.getInte ger looks up system properties and returns them as
Integer objects, assuming they exist and are convertible. If not, it
returns null, as you found out. The following will do what you want:

byte b = (byte)Integer.p arseInt("192");
System.out.prin tln(b);

Oops. That prints -64. There's that pesky sign problem again. So,
you could use

System.out.prin tln(b & 255);

which indeed prints 192. What happens is that Java fetches the byte
and sign-extends it to an int, which it passes to the println method.
And'ing it with 255 gets rid of the extended sign bits. Of course, if
we had unsigned bytes, the promotion to int would supply zeros
instead, and the extra code would not be needed.
"David Cook" <(who wants to know?)> wrote in message news:<ca******* *************@c omcast.com>...
Java's InetAddress class has some methods that use
a byte-array to hold what it describes as a 'raw IP address'.

So, I assume that they mean an array like:
byte[] ba = new byte[4];
would hold an IPv4 address.

Ok, yes, in theory, there are enough bits to hold the values.
But, my Java book clearly states that a byte is a SIGNED
quantity, is part of the Integer class, and can hold values ranging from 127
to -128.
And, my book also states that there is no 'unsigned' keyword in Java.

So, given that, how would I write code to fill each of the 4 array
elements, when I have values as large as 255 (and never any negative
values)?

Let's say I want to StringToken-ize an IP-address from a string, to load
up a byte-array with the 4 values.
I have a string (IP-address) like:
192.168.0.1
I parse out the first value (192), but when I use code like:

String str = "192";
Integer i = Integer.getInte ger(str);
byte b = i.byteValue(); //Causes NullPointerExce ption

So, what extra hoop do I need to leap thru to get each octet into
its byte? (It probably should be obvious, but not to me.)

TIA...

Dave

Jul 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3995
by: StinkFinger | last post by:
All, There are certain scripts that I have that only I want to run, both from home and sometimes work. If I add something like this (below) to the scripts, will this keep out unauthorized use (if the scripts are found somehow), or can the REMOTE_ADDR be easily spoofed ? Should I be checking HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR also ? $ip = $_SERVER; if (($ip == "x.x.x.x") or ($ip == "y.y.y.y"))
21
15718
by: Alexander N. Spitzer | last post by:
If I have a machine with 3 virtual IP addresses (192.168.1.), how can I start 3 instances of the same RMI application (each started with different properties/configs), each listening on the port 1234, but each instance binds to a different ip address. that is to say: instance #1 binds to 192.168.1.5/port 1234 instance #2 binds to 192.168.1.6/port 1234 instance #3 binds to 192.168.1.7/port 1234
2
18576
by: Darren Kirby | last post by:
Hello list: I am writing a small app in python which tracks the kernel banner at kernel.org and downloads newer kernel version(s) (if there are any). I am using GeoIP to set the download to a local mirror if there is one. This is what I use to get the local IP address: ip = socket.gethostbyaddr(socket.gethostname()) # returns: ('hostname.domain', , )
8
4598
by: YAN | last post by:
Hi, I want to get the mac address from a machine, which i have the IP address of that machine, how can i do that? I know how to get the mac address of the local machine from the following code: Dim mc As System.Management.ManagementClass Dim mo As System.Management.ManagementObject mc = New System.Management.ManagementClass("Win32_NetworkAdapterConfiguration")
6
3841
by: Paul | last post by:
Hi, Is their a client side VBscript command that I can use to post the local IP address of the machine back to my web server. I want to obtain the client's side IP address of their machine. However because my IIS stands behind a firewall and uses reverse hosting techniques, the http headers contains the firewall's IP instead of the client's. Thanks,
0
4427
by: Ricky Chan | last post by:
I am using DNSQuery API to get computer name from IP address. However, by below sample code, I don't know how to specify the DNS Address for the field (ByVal aipServers As Integer). any idea? thank you very much ar! ------- <%@ Import Namespace="System.Runtime.InteropServices" %> <%@ Import Namespace="System.Net" %>
65
21453
by: kyle.tk | last post by:
I am trying to write a function to convert an ipv4 address that is held in the string char *ip to its long value equivalent. Here is what I have right now, but I can't seem to get it to work. #include <string.h> #include <stdio.h> /* Convert an ipv4 address to long integer */ /* "192.168.1.1" --> 3232235777 */ unsigned long iptol(char *ip){
20
1566
by: Terry Olsen | last post by:
I'm writing an app that communicates with computers both inside and outside my router. So I need to determine by the remote host's IP address if I need to send them my LAN IP or my Internet IP. Someone suggested AND'ing the IP and my Subnet Mask but I come up with this: My IP: 192.168.0.14 Mask: 255.255.255.0 Result: 192.168.0.0
2
3354
by: nachotico | last post by:
hi i'm new using PHP here is what i need> i have a MySQL database that contain Decimal IPs -- the issue is that i don't know how to after extract them convert them to a real IP. here is what i have for the moment> <? $print_ip = dec2ip($row); // where the ip should go into a table
4
14719
by: hhlebanon | last post by:
I want to be able to access my trendnet ip camera from the internet without having a static IP assigned from my ISP Provider. I have a DSL Connection at home, connected to a router (trendnet) and a wirless trend net camera is connected to the router. The router ip is 192.168.0.1, the camera IP is 192.168.0.30. A) on the camera web access app i configured on the camera that the gateway is 192.168.0.1, moreover i configured the DDNS to...
0
8822
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9528
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8235
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6792
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4592
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3298
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.