Read and write to tcp socket

Hello all,

I have a requirement to read and write to a tcp socket from an HP-UX shell script. I see a /dev/tcp character device on my servers:

crw-rw-rw- 1 root root 72 0x00004f Mar 28 18:37 /dev/tcp

So I believe this is what I should use. The problem is that all the examples I find online are using /dev/tcp as a directory, not as a file. See here for an example:

Does anyone know how I interact with /dev/tcp as a character device? How do I pass the IP address and port number to it?

Thanks all

You should have a look at the nc command.

#!/bin/bash

usage="${0##*/} SERVER USER PASSWORD [PORT]"

case $1 in
    -*|"") printf "USAGE: %s\n" "$usage"; exit ;;
esac

host=${1:-mail.example.com}
user=${2:-poppy}
passwd=${3:-pop3test}
port=${4:-110}

CR=$'\r'                            ## carriage return; for removal of
exec 3<>/dev/tcp/$host/$port        ## connect to POP3 server, port 110
read ok line <&3                    ## get response from server
[ "${ok%$CR}" != "+OK" ] && exit 5  ## check that it succeeded
echo user "$user" >&3               ## send user name
read ok line <&3                    ## get response
[ "${ok%$CR}" != "+OK" ] && exit 5  ## check that it succeeded
echo pass "$passwd" >&3             ## send password
read ok line <&3                    ## get response
[ "${ok%$CR}" != "+OK" ] && exit 5  ## check that it succeeded
echo stat >&3                       ## request number of messages
read ok num x <&3                   ## get response
echo Messages: $num                 ## display number of messages
echo quit >&3                       ## close connection

3 Likes