Understanding JDK 1.6 on Ubuntu Linux IPv6 output handling - linux

I'm running Ubuntu 10.10 and my hosts configuration are as following:
root#maxim-desktop:~# cat /etc/hosts
192.168.20.20 maxim-desktop # Added by NetworkManager
192.168.10.20 maxim-lp
127.0.0.1 localhost.localdomain localhost
::1 maxim-desktop localhost6.localdomain6 localhost6
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
root#maxim-desktop:~# cat /etc/resolv.conf
# Generated by NetworkManager
nameserver 192.168.20.1
root#maxim-desktop:~# cat /etc/hostname
maxim-desktop
root#maxim-desktop:~# hostname
maxim-desktop
root#maxim-desktop:~# hostname --fqdn
root#maxim-desktop:~# ifconfig
eth0 Link encap:Ethernet HWaddr 00:1c:c0:f2:ba:89
inet addr:192.168.20.20 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fe80::21c:c0ff:fef2:ba89/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:9023854 errors:0 dropped:0 overruns:0 frame:0
TX packets:8532803 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4839992361 (4.8 GB) TX bytes:1067998152 (1.0 GB)
Interrupt:20 Memory:d3300000-d3320000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:12333251 errors:0 dropped:0 overruns:0 frame:0
TX packets:12333251 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3216352432 (3.2 GB) TX bytes:3216352432 (3.2 GB)
I'm trying to reach the same result from within java code.
Sadly, the following code just doesn't seem to cut it through.
//Copyright (c) 2011, Maxim Veksler
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Hostname and IP address info, based on JDK6 NetworkInterface
*
* #author Maxim Veksler <maxim#vekslers.org>
*/
public class NetworkUtil {
private static Logger log = LoggerFactory.getLogger(NetworkUtil.class);
public static void main(String[] args) {
System.out.println("MAC: " + NetworkUtil.getMachineMac());
System.out.println("HOSTNAME: " + NetworkUtil.getMachineHostname());
System.out.println("IP: " + NetworkUtil.getMachineIPAddress());
System.out.println("HOSTNAME ipv6: " + NetworkUtil.getMachineIPv6Hostname());
System.out.println("IP ipv6: " + NetworkUtil.getMachineIPv6Address());
}
/**
* Get the MAC address of the remote IP (if on local LAN).
* #param hostnameOrIP The target IP or Hostname (if you have DNS configured).
*
* #return MAC address if IP in local LAN, null if not.
*/
public static String getRemoteHostMac(String hostnameOrIP) {
try {
InetAddress address = InetAddress.getByName(hostnameOrIP);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(address);
return obtainMACFromAddress(networkInterface);
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain MAC address for address " + hostnameOrIP, e);
}
}
// Means we had a failure.
return null;
}
/**
* Get the machine address of the machine we are currently running on.
* #return something like 08-00-27-DC-4A-9E or null if can't obtain mac
*/
public static String getMachineMac() {
try {
return obtainMACFromAddress(getNonLoopbackNetworkInterface());
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain MAC address for localhost", e);
}
}
return null;
}
/**
* Get machine hostname, based on IPv4 configurations.
*
* #return String representing FQDN or null if can't find hostname
*/
public static String getMachineHostname() {
try {
NetworkInterface networkInterface = getNonLoopbackNetworkInterface();
Inet4Address address = getInet4Address(networkInterface);
if(address != null)
return address.getCanonicalHostName();
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain MachineHostname", e);
}
}
return null;
}
/**
* Get machine hostname, based on IPv6 configurations.
* #return String representing FQDN or null if can't find hostname
*/
public static String getMachineIPv6Hostname() {
try {
NetworkInterface networkInterface = getNonLoopbackNetworkInterface();
Inet6Address address = getInet6Address(networkInterface);
if(address != null)
return address.getCanonicalHostName();
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain IPv6Hostname", e);
}
}
return null;
}
/**
* Get machine IP, based on IPv4 configurations.
*
* #return String representing IP or null if can't find properly configured interface
*/
public static String getMachineIPAddress() {
try {
NetworkInterface networkInterface = getNonLoopbackNetworkInterface();
Inet4Address address = getInet4Address(networkInterface);
if(address != null)
return address.getHostAddress();
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain MachineIPAddress", e);
}
}
return null;
}
/**
* Get machine IP, based on IPv6 configurations.
*
* #return String representing IP or null if can't find properly configured interface
*/
public static String getMachineIPv6Address() {
try {
NetworkInterface networkInterface = getNonLoopbackNetworkInterface();
Inet6Address address = getInet6Address(networkInterface);
if(address != null)
return address.getHostAddress();
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.debug("Failed to obtain MachineIPv6Address", e);
}
}
return null;
}
/*
* ########################
* Helper private functions
*/
private static String obtainMACFromAddress(NetworkInterface networkInterface) throws SocketException {
if(networkInterface != null) {
byte[] mac = networkInterface.getHardwareAddress();
if(mac == null)
throw new Error("Failed to obtain mac address from interface: " + networkInterface.getDisplayName());
StringBuilder stringBuilder = new StringBuilder(17);
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
stringBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return stringBuilder.toString();
}
return null;
}
private static Inet4Address getInet4Address(NetworkInterface networkInterface) {
if(networkInterface != null) {
Enumeration<InetAddress> NICAddresses = networkInterface.getInetAddresses();
while(NICAddresses.hasMoreElements()) {
InetAddress address = NICAddresses.nextElement();
if(address instanceof Inet4Address)
return (Inet4Address)address;
}
}
return null;
}
private static Inet6Address getInet6Address(NetworkInterface networkInterface) {
if(networkInterface != null) {
Enumeration<InetAddress> NICAddresses = networkInterface.getInetAddresses();
while(NICAddresses.hasMoreElements()) {
InetAddress address = NICAddresses.nextElement();
if(address instanceof Inet6Address)
return (Inet6Address)address;
}
}
return null;
}
private static NetworkInterface getNonLoopbackNetworkInterface() throws SocketException {
// We need to iterate over all NIC's machine has because stupid ubuntu does not assign
// MAC address to default loopback interface...
Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
while(b.hasMoreElements()) {
NetworkInterface networkInterface = b.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress address = inetAddresses.nextElement();
if(!address.isLoopbackAddress())
return networkInterface;
}
}
// Means we haven't found any non loopback interfaces. Bummer, return empty handed.
return null;
}
}
The following is printed on my machine:
MAC: 00-1C-C0-F2-BA-89
HOSTNAME: maxim-desktop
IP: 192.168.20.20
HOSTNAME ipv6: fe80:0:0:0:21c:c0ff:fef2:ba89%2
IP ipv6: fe80:0:0:0:21c:c0ff:fef2:ba89%2
As you can see the hostname output for IPv4 & IPv6 are not the same, I wonder why should it be like this?
Also, what is the meaning of the %2 that get's attached to ipv6 related queries - Is it a bug in my code or a JVM / Linux kernel issue?
Thank you,
Maxim.

If you look at the code, here's what it does:
find a non-loopback network interface (ie. in your case, eth0)
query for the IP address of that interface (in your case, 192.168.20.20 or fe80:0:0:0:21c:c0ff:fef2:ba89%2)
resolve the IP address. As you can see from your hosts file, 192.168.20.20 correctly resolves to maxim-desktop, but there is no hostname corresponding to your IPv6 address.
IPv6 addresses beginning with fe80 (or, to be precise, addresses in the fe80::/10 network) are link-local addresses, and that %2 denotes which network interface the system should use.

Related

Node.JS dns.reverse multiple nameservers

I have an issue with my Node.JS application.
For some reason, dns.reverse is only working with the first nameserver specified and ignoring the second one.
I have the following piece of code:
import Resolver from '~/classes/resolver';
Resolver.addNameServer('192.168.2.1', '192.168.1.254').boot();
Resolver.hostnameFromIP('192.168.1.30').then((hostname: string) => {
console.log(hostname);
}).catch((error) => {
console.log(error); // We are going to end up here as the 192.168.2.1 is the first and only nameserver which will be queried
});
And here is Resolver class:
import q, { Deferred } from 'q';
import dns from 'dns';
import { ResolverInterface } from '~/classes/resolver/interfaces';
/**
* Resolver class
*/
class Resolver implements ResolverInterface {
/**
* List of nameservers used for hostname resolution
* #type { string[] }
*/
public nameservers: string[] = [];
/**
* Add nameserver for resolver to use
* #param { string } nameserver
* #return { Resolver }
*/
public addNameServer(...nameserver: string[]) : Resolver {
this.nameservers.push(...nameserver);
return this;
}
/**
* Initialize resolver
* #return { void }
*/
public boot() : void {
if (this.nameservers.length === 0) {
this.initializeWithDefaultNameServers();
}
dns.setServers(this.nameservers);
}
/**
* Resolve hostname from the IP address
* #param { string } ip
* #return { q.Promise<string> }
*/
public hostnameFromIP(ip: string) : q.Promise<string> {
const deferred: Deferred<any> = q.defer();
dns.reverse(ip, (error: NodeJS.ErrnoException | null, hostnames: string[]) => {
const defaultErrorMessage: string = 'Unable to resolve hostname';
if (error) {
return deferred.reject(defaultErrorMessage);
}
let hostname: string = hostnames.length === 0 ? defaultErrorMessage : hostnames[0];
hostname = hostname.replace('.localdomain', '').trim();
deferred.resolve(hostname);
});
return deferred.promise as q.Promise<string>;
}
/**
* Initialize resolver with default nameservers
* #return { void }
* #private
*/
private initializeWithDefaultNameServers() : void {
const nameservers: string[] = [
'192.168.0.1',
'192.168.1.1',
'192.168.2.1',
];
nameservers.forEach((nameserver: string) : void => {
this.nameservers.push(nameserver);
});
}
}
export default new Resolver;
Expected behavior:
Application should go through all specified nameservers to resolve the hostname for specified IP address
Actual behavior:
Depending on which nameserver is first, only that nameserver will be queried for the hostname.
If 192.168.2.1 is first, i can query data for 192.168.2.10, but i cannot do that for 192.168.1.30.
If 192.168.1.254 is first, i can query data for 192.168.1.30, but i cannot do that for 192.168.2.10.
Is there a way to use all specified nameservers while doing reverse hostname lookup using dns.reverse in Node.JS?
Thanks for help to Jorge Fuentes González, here is the version i've ended up using, at least it works for 2 nameservers.
/**
* Resolve hostname from IP address
* #param { string } ip
* #return { Promise<string> }
*/
public async hostnameFromIP(ip: string) : Promise<string> {
return await this.resolveForHostnameFromIP(ip)
.then((hostname: string): string => hostname)
.catch(async (error: string): Promise<string> => {
const indexOf: number = this.nameservers.indexOf(this.currentNameServer);
const newNameserverIndex: number = indexOf + 1;
if (newNameserverIndex <= this.nameservers.length - 1) {
this.currentNameServer = this.nameservers[indexOf + 1];
this.setCurrentNameServerValue();
return await this.hostnameFromIP(ip).then((hostname: string): string => hostname);
}
return error;
});
}
/**
* Helper method to resolve hostname from the IP address
* #param { string } ip
* #return { q.Promise<string> }
*/
private resolveForHostnameFromIP(ip: string) : q.Promise<string> {
const deferred: Deferred<any> = q.defer();
this.resolver.reverse(ip, (error: NodeJS.ErrnoException | null, hostnames: string[]) => {
const defaultErrorMessage: string = 'Unable to resolve hostname';
if (error) {
return deferred.reject(defaultErrorMessage);
} else {
let hostname: string = hostnames.length === 0 ? defaultErrorMessage : hostnames[0];
hostname = hostname.replace('.localdomain', '').trim();
deferred.resolve(hostname);
}
});
return deferred.promise as q.Promise<string>;
}
/**
* Update resolver configuration with current name server
* #return { void }
* #private
*/
private setCurrentNameServerValue() : void {
this.resolver.setServers([this.currentNameServer]);
};
Sorry, got the question wrong so this part is not important. Proper answer below. Btw keeping it here just in case someone has a problem like this:
That's not how DNS server lists work in almost any platform. If you look in your system network settings (Windows, Mac or Linux), surely you will see 2 nameservers (as is the default amount all ISPs provide). That's because there is a main server and a fallback server if the main one fails. You system won't return 2 different IPs when you are browsing Internet. That's weird. What your browser want is just an IP to connect to, not a list of IPs. NodeJS works the same. The rest of nameservers are just fallback ones just in case the main one fails.
Now the proper part:
When a nameserver replies with NOTFOUND, nodejs will not continue to the next nameserver, as is actually a working nameserver. Fallback nameservers are only used when the nameserver fails (with a weird error/response or a timeout. Documentation link below with this info).
To achieve what you want you need to set your nameserver, make your query, wait for the response, set the next nameserver, make your query, etc... with your current code must be an easy task. Looks pretty.
Be careful as you must not change the nameservers when a DNS query is in progress as you can read in the documentation.

How can I compile atom code through terminal using truffle?

I trying to compile my atom code through the Mac terminal and I received this error:
Error parsing /Users/owner/Desktop/contracts/contracts/ApprovalContracts.sol: ParsedContract.sol:6:36: ParserError: Expected primary expression.
address public constant approver = ; ^
Compilation failed. See above.
I need to compile my code from atom using the terminal truffle compile.
Here is the code:
pragma solidity ^0.4.18;
contract ApprovalContracts {
address public sender;
address public receiver;
address public constant approver =;
function deposit(address _receiver) external payable {
require(msg.value > 0);
sender = msg.sender;
receiver = receiver;
}
function viewApprover() external pure return(address) {
return(approver);
}
function approve() external {
require(msg.sender == approver);
receiver.transfer(address(this).balance);
}
}
There are a few problems with your code.
You have to initialize the constant variable approver with a value.
On line 12, the code should be receiver = _receiver;
On line 15, it should be returns(address) instead of return(address)
The final code should be something like this
pragma solidity ^0.4.18;
contract ApprovalContracts {
address public sender;
address public receiver;
address public constant approver=some-address-here-without-quotes;
function deposit(address _receiver) external payable {
require(msg.value > 0);
sender = msg.sender;
receiver = _receiver;
}
function viewApprover() external pure returns(address) {
return(approver);
}
function approve() external {
require(msg.sender == approver);
receiver.transfer(address(this).balance);
}
}

tomcat access log get my eth0 ip?

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%t %a %A %p %r %q %s %B %D %{User-Agent}i %{Referer}i"
resolveHosts="false" />
This is my server.xml ,then i found the result is like this:
[29/Mar/2017:10:36:16 +0800] 192.168.5.149 127.0.0.1 80 GET /favicon.ico HTTP/1.1 404 0 0 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0 -
in the server.xml %A just give me the loop ip, but i want eth0 ip ..
So what should i do? Thanks a lot!
Check host name:
$ hostname
yourhost
Edit /etc/hosts and add:
192.168.5.1 yourhost
FYI, Tomcat source code:
/**
* write local IP address - %A
*/
protected static class LocalAddrElement implements AccessLogElement {
private static final String LOCAL_ADDR_VALUE;
static {
String init;
try {
init = InetAddress.getLocalHost().getHostAddress();
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
init = "127.0.0.1";
}
LOCAL_ADDR_VALUE = init;
}
#Override
public void addElement(StringBuilder buf, Date date, Request request,
Response response, long time) {
buf.append(LOCAL_ADDR_VALUE);
}
}

TCP client server in C#, it doesn't show anything, neither it is connecting

I am trying to connect to TCP client but seems to be not working, following is my code snippet, when I am running this application ,It doesn't show IP it is running and the port it is listening to.
public class serv {
public static void Main() {
try {
IPAddress ipAd = IPAddress.Parse("172.21.5.99");
// use local m/c IP address, and
// use the same in the client
TcpListener myList=new TcpListener(ipAd,8001);
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt {
public static void Main() {
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("172.21.5.99",8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Brother,
you didn't specified the start
after this line
TcpListener myList=new TcpListener(ipAd,8001);
put
myList.Start();
this is for listening the port
Hope this works !

"Only one usage of each socket address (protocol/network address/port) is normally permitted"

I am trying to do some network programming with a simple client and a server that is given to me. When my client gets connected to the server ,server prints message "Only one usage of each socket address (protocol/network address/port) is normally permitted"
The port that I am using is 6000 and localhost is the host.
I am using a Tcp client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace ConsoleTankClientVersion1
{
class Program
{
static void Main(string[] args)
{
TcpClient client = null;
NetworkStream netStream = null;
//server ip
String server = "127.0.0.1";
//server port
int servPort = 6000;
//The input string is converted to a stream of bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes("JOIN#");
try
{
// Create socket that is connected to server on port 6000
client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending join string");
netStream = client.GetStream();
// Send the encoded string to the server
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd = 0; // Bytes received in last read
// Receive the same string back from the server
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0)
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
TcpTimedWaitDelay is 30 s
Max user port value is 60000

Resources