• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3057
  • Last Modified:

What port is ping?

What port does ping use?

This seems like a simple question, but I cannot find a definitive answer.

Linux manual page for ping mentions an ECHO_REQUEST datagram:

"Ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway.  ECHO_REQUEST datagrams (``pings'') have an IP and ICMP header, followed by a ``struct timeval'' and then an arbitrary number of ``pad'' bytes used to fill out the packet."

I searched the include directory and found this C preprocessor define:
#define ICMP6_ECHO_REQUEST          128

I also found this in a document someone gave me:

*   128/tcp GSS X License Verification
*   128/udp GSS X License Verification

And, finally, in the RFC 1060 specification, I found this:

7       ECHO       Echo                                  [95,JBP]

What I'm trying to do is write a ping program in Java, if that's at all possible.  I know that the standard ping uses the ICMP (Internet Control Message Protocol) which is a low-level network administration protocol not supported in Java nor in Microsoft's Winsock.  ICMP on Win32 is provided by an unsupported and undocumented library icmp.dll.  I also know that it's sending an ICMP datagram.

However, all ping does is simply send a message to the host and report if it arrived.  That takes all of three lines of code in Java.  But, it's not working for most of the hosts I've tried where the standard ping program does.  I keep getting an exception of "Connection refused" every time.

These are the port numbers I've tried:

7   Echo service
13  Daytime
23  Telnet

There may be some other reason why my Java ping program fails where the standard ping succeeds, but trying every possible port number with a range of hosts is impractical.  By knowing definitively what port ping uses, I can eliminate the other factors.

I'm asking this question in the Java area because I think the answer would benefit this community most, not because I think a Java expert would necessarily know the answer (I may be wrong, if so I apologize).  So, I've referenced this question in several other topic areas.
1 Solution
as you already know ICMP is low-level network protocol, which is not directly supported in Java.

in Java you can use TCP packets and UDP datagrams - both of them are relatively hi-level (and work over IP) (for TCP connection you need not only working network connection, but remote server app that listens on some port)


(Sect. 15) How can I write the "ping" program?
 You can't do it directly. Quoting from the Java Networking FAQ,
Ping requires ICMP packets. These packets can only be created via a socket of the SOCK_RAW type. Currently, Java only allows SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets. It seems unlikely that this will be added very soon, since many Unix versions only allow SOCK_RAW sockets to be created by root, and winsock does not address ICMP packets (win32 includes an unsupported and undocumented ICMP.DLL).
You could write a program that handshakes with a remote system, to simulate ping, or you could use native code for the raw socket. Other sites:
You can find the Java Networking FAQ at http://www.io.com/~maus/JavaNetworkingFAQ.html
There is an additional Java Networking FAQ (which is being modified and reposted regularly) at http://www.davidreilly.com/java/java_network_programming/
Packet InterNet Groper (sorry, just found out the name, so had to use it) is handled before/below it ever gets to a port.
I actually wrote this code.

Here is the java part.

  This was written by Artimage@ishiboo.com for Appnet.com
  This software (and its source code) are freely usable, modifiable,
  and redistributable under the terms of the GNU General Public License,
  available at http://www.gnu.org/copyleft/gpl.html, and in the ./COPYING
  file in the MARS distribution.

package org.altara.mars;

import java.net.*;
import java.io.*;

   Use ICMP to check if a machine is up.

public class PINGProbe extends Probe {
    public native boolean nativePing(String fqdn);

// Other stuff that is unimportant here

Here is the c part

   Native code for a ICMP probe to be used in java.

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>

#include <jni.h>
#include <stdio.h>
#include <errno.h>
#include "PINGProbe.h"

#define MAX_BUFF 2046  

extern int h_errno;

/*  Probes the host, returns the result. The results should be interpreted
  as follows: true means the probe is OK (set status to Host.OK), false
  means the probe has timed out (set status to Host.TO), and if an
  exception is thrown, the probe failed outright (set status to Host.FAIL)

Java_PINGProbe_nativePing(JNIEnv *env, jobject obj, jstring fqdn)
  const char * hostName;
  int s;
  struct hostent * host;
  struct sockaddr_in hostAddr;
  struct icmphdr ihdr;
  char * data;
  int dataLen;

  // BUGBUG Add code to check euid

 // Allocate memory for structures.
  if ( NULL == (host = (struct hostent *) malloc(sizeof(struct hostent))) ) {
    perror("Malloc failed:");

  // Convert from java string to ascii
  hostName = (*env)->GetStringUTFChars(env, fqdn, 0);
  printf("%s", hostName);
  // Convert hostname to address.
  if( NULL == (host = gethostbyname(hostName))) {
    // Call failed.
    perror("error gethostbyname: ");

    // BUGBUG all of these failure returns should be throwing an exception
    //        instead.
    return 0;

  // Release Java string
  (*env)->ReleaseStringUTFChars(env, fqdn, hostName);
  bzero((char *)&hostAddr, sizeof (hostAddr)); // zero out structure.
  // Copy address to address structure.
  bcopy(host->h_addr, (char *) &hostAddr.sin_addr, host->h_length);
  hostAddr.sin_family = host->h_addrtype;

  // create a raw socket
  if ( -1 == (s = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) ) {
    perror("Socket creation failed:");
    return 0;

  // Connect to host.
  if ( -1 == connect(s, (struct sockaddr *)&hostAddr, sizeof(hostAddr))){
    perror("Connect failed:");
    return 0;

  // Get a buffer ready to store incoming data
  if ( NULL == (data = (char *)malloc(MAX_BUFF))) {
    perror("Malloc failed:");
    return 0;

  dataLen = sizeof(data);

  // Create the icmp header.
  ihdr.type = ICMP_ECHO;
  ihdr.code = 0;
  ihdr.checksum = 0;
  ihdr.un.echo.sequence = 1;
  ihdr.un.echo.id = 42;

  // Loop until we succeed or 4 times..

  // Do a Send
  send(s, &ihdr, sizeof (ihdr), 0);

  // BUGBUG we should set the timeout.. Get it from mars.

  // Start listening for our ping to come back.    
  dataLen = recv(s, data, dataLen, 0);
 if (-1 == dataLen) {
    perror("recv error:");
    return 0;
  // Close the connection

  return 1;

#ifdef 0
  This is my test driver.
int main (int argc, char ** argv)
  int r;

  if (argc != 2) {
    printf("Usage: %s hostname\n", argv[0]);

  printf("Here we go.\n");
  r = nativePing(argv[1]);
  printf("Done. %d \n", r);



You will need to figure out how to link these on your system though.

Look at this site.


Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

you can always use telnet on a different port
IE, trying from an unix box to contact a W98 with no service daemon (BUT port 139 is always surveyed on W)

root@med1091[/]telnet 139
Connected to
Escape character is '^]'.

the connected response indicate this port on this address is active;
BUT, is necessary to know a surveyed port !
i think chensu clarified it a bit already.

but u can follow this nice little thread
titled 'ICMP Well-Known Port'

for more...
cpopinAuthor Commented:
Your first URL answered my question.  Your third URL looks like a good resource for Java FAQs.


-- CPopin
cpopinAuthor Commented:
chensu didn't comment on this thread.
yeah ,I know he commented in C++ section but i was going thru that yesterday,and saw ur link from there to here.
cpopinAuthor Commented:
Yah, I noticed it too after reading more of my e-mail.  Not everyone is understands the reason for thread referencing.  You do that so that experts in other threads can all contribute to a single thread in the most proper topic area.  No one's supposed to comment on those zero point referencing threads.  They're supposed to comment in only the original thread (this one).  It makes for a more valuable PAQ.

Once the original thread becomes a PAQ, the referencing threads should be deleted.
cpopinAuthor Commented:
If a packet hits a pocket on a socket on a port,
and the bus is interrupted and the interrupt's not caught,
then the socket packet packet has an error to report.

-- Programmer's traditional nursery rhyme
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now