Download Socket Programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Socket Programming
Some examples in C/C++
Some examples in Java
1
The most general mechanism for communication offered by
Berkeley Unix is the socket. (winsocket for windows).
Two processes communicate by creating sockets and sending
messages between them.
A socket appears to be like a file descriptor on which users can
read, write, and perform input/output control.
Sockets can be used in a single computer for interprocess
communication (the Unix domain) and for communication across
computer systems (the Internet domain).
2
Types of socket vary based on the way socket’s address space is
defined and the type of communication designed.
Usually, a triple that includes domain, type and protocol defines a
socket address.
The most common domain are AF UNIX (for Unix path name),
AF INET (for Internet addresses) and AF OSI (as specified by
international standards for OSI).
The various address formats are defined as constants in
sys/socket.h
3
Usually 0 indicate the use of the default protocol for the chosen
domain and type. For example, when TCP is used, the type
SOCK STREAM is for domain AF UNIX. When UDP is used, the type
SOCK RAW is used for domain AF UNIX.
For communicating between sockets, a three-component
interlocutor consisting of IP address, port, and protocol is defined.
A socket is created with the call:
sd = socket(domain, type, protocol)
For example:
if ((sd = socket(AF\_INET, SOCK\_DGRAM, 0) < 0)
{ perror("socket"); exit(1);}
4
An address is provided with bind system call, which has three
parameters: sock, address, addrlen.
status = bind (int sd, struct sockaddr *address, int
addrlen)
Internet library and DNS are also useful for client-server program.
#include <sys/types.h>
#include <netinet/in.h>
5
Socket connection between a client and a server using TCP follows
the steps:
Server:
Create end point (socket())
Bind address bind())
Specify queue (listen())
Wait for connection (accept())
Transfer data (write(), read())
6
Client:
Create end point (socket())
Connect to server (connect())
Transfer data (write(), read())
When UDP is used, usually can use sendto(), recvfrom()) to
transfer data.
7
#include
#include
#include
#include
#include
<sys/types.h>
<sys/socket.h>
<netinet/in.h>
<netdb.h>
<stdio.h>
char *message() =
{
"Some message from client, \n",
"some more message.\n ",
"<end>\n"’
0
};
8
main (argc, argv)
int argc;
char *argv[];
{
char c;
FILE *rfp, *wfp;
char hostname[64];
register int i,s;
struct hostent *hp;
struct sockaddr_in sin;
char buffer[128];
if (argc !=2)
{
fprintf(stderr, "usage: %s <port number>\n",argv[0]);
exit(1);
}
9
gethostname (hostname, sizeof(hostname));
if ((hp=gethostbyname(hostname)) == NULL)
{ ... ...}
if ((s=socket(AF_INET,SOCK_STREAM,0)) < 0)
{ ... ... }
sin.sin_family=AF_INET;
sin.sin_port=htons(atoi(argv[1])));
bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);
if (connect(s, &sin, sizeof(sin)) < 0)
{ ... ...}
rfp=fdopen(s,"r");
10
wfp=fdopen(s,"w");
do
{
fgets(buffer, sizeof(buffer), rfp);
printf("%s", buffer);
}
while (buffer[0] !=’.’);
for (i=0;message[i];i++)
fprintf(wfp, %s%, message[i]);
ffluch(wfp);
close(s)
exit(0);
}
11
Java has a package java.net to create TCP/IP connection
between two applications. The class Socket is the central element
of this package.
For a sever to start listening to some port, a class ServerSocket is
used.
Serversocket serverSocket = new ServerSocket(port);
For a client to connect to a server, client also creates a socket.
Socket clientSocket = new Socket(host,port);
To receive and send messages, use InputStream, OutputStream
which are classes in the package java.io
12
import java.security.*;
import java.math.*;
import java.net.*;
import java.io.*;
public class DiffieHellmanInitiator {
static BufferedReader k=new BufferedReader(new
InputStreamReader(System.in));
public static void main(String[] args) throws
IOException {
//Make a safe prime and generator
SecureRandom sr=new SecureRandom();
PrimeGenerator pg=new PrimeGenerator(1025,10,sr);
BigInteger[] pandg=pg.getSafePrimeAndGenerator();
//Make your secret exponent
BigInteger x=new BigInteger(pandg[0].bitLength()-1,sr);
//Raise g to this power
13
BigInteger gtox=pandg[1].modPow(x,pandg[0]);
//Open a connection with a server waiting for info
System.out.println("Enter host name or IP address
of server:");
String host=k.readLine();
//Server should be listening on port 11111
Socket socket=new Socket(host,11111);
//Open input and output streams on the socket
BufferedReader in=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintStream out=new PrintStream(socket.getOutputStream());
//Send the values p,g,gtox to server
out.println(pandg[0]);
out.println(pandg[1]);
out.println(gtox);
//Get the gtoy value from server
14
BigInteger gtoy=new BigInteger(in.readLine());
//Raise gtoy to x power-this is the secret key
BigInteger key=gtoy.modPow(x,pandg[0]);
System.out.println("The secret key is:\n"+key);
k.readLine();
}
}
Note: This program is just used as an example. To rum this
program, some dependent classes are required:
PrimGenerator.java, BigIntegerMath.java.
15