现在的位置: 首页 > 综合 > 正文

Socket

2013年09月13日 ⁄ 综合 ⁄ 共 4434字 ⁄ 字号 评论关闭
文章目录

 

The socket
system call returns a descriptor that is in many ways similar to a low-level file descriptor. When the socket has been connected to another end-point socket, you can use the read
and write
system calls with the descriptor to send and receive data on the socket. The close
system call is used to end a socket connection.

 

Socket Addresses

Each socket domain requires its own address format. For an AF_UNIX socket, the address is described by a structure, sockaddr_un
, defined in the sys/un.h
include file.

In the AF_INET domain, the address is specified using a structure called sockaddr_in
, defined in netinet/in.h
, which contains at least these members:

The IP address structure, in_addr
, is defined as follows:

The for bytes of an IP address constitute a single 32-bit value; An AF_INET socket is fully described by its domain, IP address, and port number. From an application's point of view, all sockets act like file descriptors and are addressed by a unique integer value.

 

Naming a socket

 

Creating a socket queue

 

Accepting connections:

The accept
system call returns when a client program attempts to connect to the socket specified by the parameter socket
. The client is the first pending connection from that socket's queue. The accept
function creates a new socket to communicate with the client and returns its descriptor. The new socket will have the same type as the server listen socket.

 

The socket must have previously been named
by a call to bind
and had a connection queue allocated by listen
. The address of calling client will be placed in the sockaddr
structure pointed by address
. A null pointer may be used here if the client address isn't of interest.

 

The address_len
parameter specifies the length of the client structure.Before calling accept
, addresss_len
must be set to the expected address length. On return, address_len
will be set to the actural length of the calling client's address structure.

Requesting connections :

 

Closing a socket:

You can just terminate a socket connection at the server and client by calling close
, just as you would for low-level file descriptors.

 

例子:

client.c:

 

server.c

The function, inet_addr,
convert the text representation of an IP address into a form suitable for socket addressing.

 

 

Host and network byte ordering:

Client and server programs must convert their internal integer representation to the network ordering before transmission.

hronl : host to network long

 

So in the server.c:

and in the client.c:

抱歉!评论已关闭.