Socket

 

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值