Port to Service Name in Java? - java

My services file (C:\WINDOWS\system32\drivers\etc\services) has a bunch of Port to Service mappings:
echo 7/tcp
echo 7/udp
discard 9/tcp sink null
discard 9/udp sink null
systat 11/tcp users #Active users
systat 11/udp users #Active users
daytime 13/tcp
daytime 13/udp
qotd 17/tcp quote #Quote of the day
qotd 17/udp quote #Quote of the day
chargen 19/tcp ttytst source #Character generator
I am trying to find a way to convert from a Port to the Service Name programmatically through Java APIs (instead of parsing) or third party libraries?
Pseudocode:
Port port = new Port("443","tcp");
String service = port.getService();
System.out.println(service); //prints "https"
Is there any good way to accomplish this?

What you are looking for is a Java implementation of the Linux getservbyport() system call. Take a look at http://github.com/wmeissner/jnr-netdb. Also, do a Google search for java getservbyport

I don't think there is some API in java for this purpose.
You will either need to parse this file or maintain port service mapping in some form (Properties file,db etc.).
example to parse from system file is :
http://www.javafaq.nu/java-example-code-162.html

Related

Originate call to sip trunk via asterisk manager api java

So I am a total newbie in asterisk and managing call lines in general but I managed to install Asterisk Now 13 distro, I have connected 2 sip phones with pjsip and configured a sip trunk which works when I dial an external number with the corresponding prefix. Now I have to programmaticly originate calls and connect them to local extensions which I have no idea how to achieve and I cant seem to find much information about it on the internet after hours of searching.
I managed to connect 2 local sip phones with the asterisk manager api and OriginateAction in the following way:
originateAction = new OriginateAction();
originateAction.setChannel(ConnectionType+"/"+extCaller);
originateAction.setContext(context);
originateAction.setCallerId(idCaller);
originateAction.setExten(tDestination);
originateAction.setPriority(priority);
originateAction.setTimeout(timeoutCall);
managerConnection.login();
originateResponse = managerConnection.sendAction(originateAction, timeoutRequest);
I also tried this channel originate pjsip/201 extension number#from-ptsn and channel originate local/201#from-local extension number#trunkName .
The context of the PJSIP trunk is from-pstn,I tried using that in various ways without luck both in asterisk cli and the application.
How do I make it use the PJSIP trunk when originating the call and make a call out of the office?
EDIT: I originated an outgoing call using a number that completes with the trunk outgoing route requisites and the "from-internal" context like this:
channel originate Local/201#from-internal extension (prefix)numberToCall#from-internal
I still do not understand why this works and if it is the correct answer to my question.
So the answer is in the edit of the question. The only way to generate an outgoing call that I could find is to originate that call "internaly" (with the context "from-internal" which happens to be the same context that is used when originating internal calls) introducing a target number value that completes with the sip trunk's route pattern requirements.
Example:
I have a route configured for the sip trunk( trunk1 ) with a pattern(RegEx): [0]{1}/number/ that means that with a 0 infront of any nubmer it will be a valid value for that route and it will try to call using trunk1.
In the case of AsteriskNow CentOS installation it happens to be with the context "from-internal". Since the asterisk configuration files are owned by the FreePBX it is recomended to use the FreePBX GUI instead of configuring the .conf files of asterisk manualy.
That concludes to :
channel originate Local/201#from-internal extension (0)[numberToCall]#from-internal
Which will make the extension 201 ring first and when picked up it will try to use the sip trunk to dial that [numberToCall] because the route with the 0 is "called".
In order to send that command to asterisk using asterisk-java I wrote the following code:
ManagerConnectionFactory factory = new
ManagerConnectionFactory("serverIp", "username",
"passwd");
ManagerConnection managerConnection=factory.createManagerConnection()
OriginateAction originateAction=new OriginateAction();
final String randomUUID=java.util.UUID.randomUUID().toString();
System.out.println("ID random:_"+randomUUID);
originateAction.setChannel([connectionType]+"/"+[callerExtension]);<-- SIP or PJSIP / 201(the phone that will ring first)
originateAction.setContext("from-internal"); <-- Default FreePBX context
originateAction.setCallerId([callerId]); // what will be showed on the phone screen (in most cases your phone)
originateAction.setExten([targetExten]); //where to call.. the target extension... internal extension or the outgoing number.. the 0[nomberToCall]
originateAction.setPriority([priority]);// priority of the call
originateAction.setTimeout(timeoutCall); // the time that a pickup event will be waited for
originateAction.setVariable("UUID", randomUUID); // asigning a unique ID in order to be able to hangup the call.

How to change proxy programmatically?

I wish to test my web server which have checking to detect abusive API usage by IP address. One IP address is limited to a few hundred API calls per day.
As part of testing & simulation procedure, I need to be able to switch IP frequently & programmatically. How to do this? I am thinking of using publicly available free proxy service (or even TOR) to hide my IP. But I am not sure how to change the proxy settings programmatically.
I am using Ruby but any languages are welcome.
In ruby you can make calls to the command prompt. If I were you I would make a method that uses these calls. To do this use %x command.
Edit----
This is the code I made.
def ipChanger(name,ip)
return %x(netsh interface ip set address #{name} static #{ip} 255.255.255.0)
end
The syntax is "netsh interface ip set address "Your adapter name here" static "new ip" "new netmask" "optional default gateway"

Trying to get InetAddress.getLocalHost.getHostAddress (Java/Scala) to return external IP

So I'm having a problem with using InetAddress.getLocalHost.getHostAddress to get the external IP address of a given machine.
I'm actually doing this in Scala in a sense - the configuration file for Akka Remote Actors default uses InetAddress.getLocalHost.getHostAddress to get the IP address of the machine, which is what I want since I will be deploying the actors on several machines. However, it seems to be returning 127.0.0.1 instead of the external IP address I want (since the remote actors need to communicate back and forth across the netwrok).
The problem is that I can't use any of the methods I've found on Google to circumvent this since they all seem to involve adjusting the code itself, whereas here I don't really have any code to adjust, the DSL just automatically uses InetAddress.getLocalHost.getHostAddress.
I've read on a few threads from a Google search that you can circumvent this by editing your host file or something? How do I do this?
Thanks!
-kstruct
You may want to use NetworkInterface class.
In particular, use static getNetworkInterfaces method to enumerate all available network interfaces.
Check your /etc/hosts file. It should map 'localhost' to 127.0.0.1 and your real hostname to your real IP address, or one of them :-| Some Linux distributions get this wrong apparently.
i got a partial solution if getLocalHost doesn't works.
this solution have the problem that you must to know the name of your network interface in order to match the real one. Maybe you can improve this code removing "virtual" devices and something else.
This is scala code, but java code is very similar
def returnInterfaceAddress() : InetAddress = {
var myInetAddress = InetAddress.getLocalHost
val interfaces : util.Enumeration[NetworkInterface] = NetworkInterface.getNetworkInterfaces()
while(interfaces.hasMoreElements){
val inter = interfaces.nextElement()
if(inter.getDisplayName() == "Realtek PCIe GBE Family Controller"){
myInetAddress = inter.getInetAddresses().nextElement()
}
}
myInetAddress
}

What is the easiest way to create a HostAndPort-Instance if the hostname is "localhost"?

I want to use the class HostAndPort from guava, to store a host and a port. What is the easiest way to create a valid HostAndPort-Instance, if the host is "localhost" and not "127.0.0.1" ?
It tried HostSpecifier.isValid(String) to validate the host, before i create a HostAndPort-Instance, but it returns false for "localhost". So in my case i can't use HostSpecifier, except i transform "localhost" to "127.0.0.1".
Is there an other way to validate a host name without a DNS-lookup?
java.net.InetAddress.getByName(String hostname) is the one. http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html
The local address lookups are done via lmhosts on windows if enabled and on linux/unix using name service switch config(/etc/nsswitch.conf) in order to check where to lookup first - files,dns,nis.... and so on (man nsswitch.conf). The java api call will resolve it depending on a system configuration.
EDIT:
you probably want to take a look at this library too
http://www.xbill.org/dnsjava/
hope this helps abit.

Querying the DNS service records to find the hostname and TCP/IP

In a paper about the Life Science Identifiers (see LSID Tester, a tool for testing Life Science Identifier resolution services), Dr Roderic DM Page wrote :
Given the LSID urn:lsid**:ubio.org**:namebank:11815, querying the DNS for the SRV record for _lsid._tcp.ubio.org returns animalia.ubio.org:80 as the location of the ubio.org LSID service.
I learned that I can link _lsid._tcp.ubio.org to animalia.ubio.org:80 using the host command on unix:
host -t srv _lsid._tcp.ubio.org
_lsid._tcp.ubio.org has SRV record 1 0 80 ANIMALIA.ubio.org
How can I do this 'DNS' thing using the Java J2SE API (Without any external java library, I'd like a lightweight solution ) ?
Thank you
The JNDI DNS provider can lookup SRV records. You need to do something like:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns:");
DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes("_lsid._tcp.ubio.org", new String[] { "SRV" });
The returned attributes are an enumeration of strings that look like "1 0 80 ANIMALIA.ubio.org". The space separated fields are in order:
priority
weight
port
server
You can't do this using the standard Java libraries. The InetAddress class is only capable of looking up DNS A records.
To look up SRV records (and indeed any other DNS resource record type other than an A record) you need a third party library. dnsjava is the usual option.
I've personally used the 1.6 version on Google Android, it works fine. Version 2.0 and later use the Java nio layer, so won't be compatible with earlier JVMs.
I think you can't do it without using some external libraries. java.util.InetAddress has some methods to resolve names via DNS, but it's only usable for resolving names into IP addresses and not for generic DNS querying.
For that, you need some external library like DNSJava.
In case anybody is looking for non-Java solutions (which they might given that the title of the question isn't language specific), when I implemented a LSID (see doi:10.1186/1751-0473-3-2) I used the PEAR package Net_DNS, which can look up SRV records.

Categories

Resources