windows套接字相关函数
作者:vpoet
mail:vpoet_sir@163.com

我们学习TCP/IP协议无非是利用这些协议进行通信开发,然而如果让我们自己来直接根据协议规则和协议格式来进行网络开发无疑
是一件十分痛苦的事情,显然为了减轻程序员的开发负担,windows提供给我们一套网络开发的API,这个API族就叫做套接字库。
但是套接字和TCP/IP协议到底是什么关系呢。
我们暂且可以这样理解,如图:


那么OK,理解不了我们也暂且这样理解吧。接下来我们讲讲使用套接字编程主要用到API




1:socket
MSDN这样描述:

The Windows Sockets socket function creates a socket that is bound to a specific service provider.

SOCKET socket(
int
af,
int
type,
int
protocol
);
 

Parameters

af
[in] Address family specification.
type
[in] Type specification for the new socket.

The following are the only two type specifications supported for Windows Sockets 1.1:

Type Explanation
SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams with an OOB data transmission mechanism. Uses TCP for the Internet address family.
SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family.

In Windows Sockets 2, many new socket types will be introduced and no longer need to be specified, since an application can dynamically discover the attributes of each available transport protocol through the
WSAEnumProtocols function. Socket type definitions appear in Winsock2.h, which will be periodically updated as new socket types, address families, and protocols are defined.

protocol
[in] Protocol to be used with the socket that is specific to the indicated address family. 


该函数创建一个套接字,参数af为协议族类型AF_INET为TCP/IP协议族
type为套接字类型,有两种类似SOCK_STREAM为使用TCP进行通信 SOCK_STREAM为使用UDP进行通信
protocol可以为IPPROTO_TCP或IPPROTO_IP,此参数英语type保存一致
举例:SOCKET S;
 S=socket(AF_INET,SOCK_STREAM,IPPOTO_TCP)表示使用TCP协议进行通信






2.bind
顾名思义即绑定,用过套接字编程的都知道,当我们编写服务端程序的时候需要使用该函数
MSDN这样描述:

The Windows Sockets bind function associates a local address with a socket.

int bind(
SOCKET
s,
const struct sockaddr FAR
*name,
int
namelen
);
 

Parameters

s
[in] Descriptor identifying an unbound socket.
name
[in] Address to assign to the socket from the SOCKADDR structure.
namelen
[in] Length of the value in the name parameter.

Return Values

If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.

该函数将一个本地的地址绑定到一个套接字上,如果绑定不错位,将返回0,否则将返回SOCKET_ERROR
参数s为需要绑定的套接字
参数*name为一个常量sockaddr结构,但是一般情况下我们都使用sockaddr_in结构
其结构定义如下:
struct
sockaddr_in {
  short int sin_family; /* Address family */
  unsigned short int sin_port; /* Port number */
  struct
sin_addr sin_addr; /* Internet address */
  unsigned char sin_zero[8]; /* Same size as struct sockaddr */
  };
  sin_family:指代协议族,在socket编程中只能是AF_INET
  sin_port:存储端口号(使用网络字节顺序)
  sin_addr:存储IP地址,使用in_addr这个数据结构
  sin_zero:是为了让sockaddr与sockaddr_in两个数据结构保持大小相同而保留的空字节。
其中sin_addr定义
typedef
struct in_addr {
  union {
  struct{ unsigned char s_b1,s_b2, s_b3,s_b4;} S_un_b;
  struct{ unsigned short s_w1, s_w2;} S_un_w;
  unsigned long S_addr;
  } S_un;
  } IN_ADDR;

一般我们这样用
addrs.sin_addr.S_addr=inet_addr("192.168.1.110")
函数inet_addr可以把字符串直接转换成in_addr类型
也可以使用inet_ntoa()将in_addr类型转换为字符串类型
参数namelen即为name的长度 即sizeof(name)
举个典型的例子:
SOCKET s;
s=socket(AF_INET,SOCK_STREAM,IPPOTO_TCP);
sockaddr_in addrbindto;
addrbindto.sin_family=AF_INET;
addrbindto.port=htons(8001)
htons是将u_short类型转换为网络字节序,htonl是将u_long类型转换为网络字节序
addrbindto.sin_addr_S_addr=inet_addr("192.168.1.110")
bind(s,(
const struct sockaddr
)&addrbindto,sizeof(addrbindto))


3.listen

The Windows Sockets listen function places a socket a state where it is listening for an incoming connection.

int listen(
SOCKET
s,
int
backlog
);
 

Parameters

s
[in] Descriptor identifying a bound, unconnected socket.
backlog
[in] Maximum length of the queue of pending connections. If set to SOMAXCONN, the underlying service provider responsible for socket s will set the backlog to a maximum reasonable value. There is no standard provision to obtain the actual backlog value.

Return Values

If no error occurs, listen returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

该函数在指定的套接字上监听连接请求,参数s为监听的套接字,backlog表示表示允许的最大连接数

举例:
listen(s,5);




4.connect

The Windows Sockets connect function establishes a connection to a specified socket.

int connect(
SOCKET s,
const struct sockaddr FAR *name,
int namelen
);
 

Parameters

s
[in] Descriptor identifying an unconnected socket.
name
[in] Name of the socket to which the connection should be established.
namelen
[in] Length of name

该函数对一个指定的套接字建立连接

参数s为想要建立连接的套接字
name为sockaddr类型的指针
namelen即为sizeof(name)

举例:
SOCKET s;
sockaddr_in conaddr;
s=socket(AF_INET,SOCK_STREAM,IPPOTO_TCP);
conaddr.sin_family=AF_INET;
conaddr.port=htons(8001) htons是将u_short类型转换为网络字节序,htonl是将u_long类型转换为网络字节序
conaddr.sin_addr_S_addr=inet_addr("192.168.1.110")
connect(s,(const struct sockaddr)&conaddr,sizeof(conaddr))



5.send

The Windows Sockets send function sends data on a connected socket.

int send(
SOCKET
s,
const char FAR
*buf,
int
len,
int
flags
);
 

Parameters

s
[in] Descriptor identifying a connected socket.
buf
[in] Buffer containing the data to be transmitted.
len
[in] Length of the data in buf.
flags
[in] Indicator specifying the way in which the call is made. 


该函数用于向已连接的套接字发送数据
参数s为一个连接到的套接字
参数buf为发送数据的缓存
参数len为发送缓存数据的长度

举例:
char buf[20]="hello123";
send(s,(const char *)buf,sizeof(buf))



5.recv

The Windows Sockets recv function receives data from a connected socket.

int recv(
SOCKET s,
char FAR *buf,
int len,
int flags
);
 

Parameters

s
[in] Descriptor identifying a connected socket.
buf
[out] Buffer for the incoming data.
len
[in] Length of buf

该函数为接受函数:
参数与send类型,不在赘述



6. recvfrom,sendto
这两个函数功能与send与recv类似,只是它们用于UDP通信中



OK,主要函数先介绍到这儿,等下篇博文我们亲自动手来写一个基于TCP的简单CS通信小Demo

windows套接字相关函数的更多相关文章

  1. 缺少网络连接需要的Windows套接字注册表项(浏览器无法连网)

      缺少网络连接需要的Windows套接字注册表项(浏览器无法连网) CreateTime--2018年4月25日14:17:42 Author:Marydon 1.异常信息 此计算机上缺少一个或多个 ...

  2. 基于Windows的套接字相关函数及示例

    链接ws2_32.lib库 头文件#include <winsock2.h> int WSAStartup(WORD wVersionRequested,LPWSADATA lpWSADa ...

  3. Windows套接字Socket函数

    1.使用套接字函数之前,先要加载套接字函数库: #include "Winsock2.h" #pragma comment(lib,"Ws2_32.lib") ...

  4. windows套接字阻塞模式编程实例

    一.阻塞模式套接字服务端和客户端的运行流程如下: 1.1 服务器运行过程如下: 1.服务器启动后,等待客户端的连接请求.2.当收到客户端的请求后,在界面上显示该客户端的IP地址和端口,以及“Hello ...

  5. Windows进程间通讯(IPC)----套接字

    Windows套接字 Windows套接字即socket,通过socket可以实现在不同的进程间通信,甚至这两个进程可以不在同一个计算机中. Winsock使用步骤 服务端 socket初始化 创建套 ...

  6. 套接字编程(VC_Win32)

    简介(源于维基) Berkeley套接字(也作BSD套接字应用程序接口)刚开始是4.2BSD Unix操作系统(于1983发布)的一套应用程序接口.然而,由于AT&T的专利保护着UNIX,所以 ...

  7. VC远控(一)界面设计及套接字连接测试

    首先创建一个MFC项目. 选择基于对话框: 勾选Windows套接字 依次拉上各种不同的控件: Edit Control.Button.Tree.Static Text.List.Progress C ...

  8. CAsyncSocket create创建套接字失败

    解决方法: 在继承CAsyncSocket 类的子类的构造函数中加入以下代码: if (!AfxSocketInit()) AfxMessageBox(IDP_SOCKETS_INIT_FAILED) ...

  9. C项目实践--网络协议和套接字编程

    1.TCP/IP协议 TCP/IP协议是一组包括TCP协议和IP协议,UDP(User Datagram Protocol)协议,ICMP(Internet Control Message Proto ...

随机推荐

  1. vb串口通信界面

    界面如上: 程序如下: Dim num As Byte     '申明一个全局变量为单字节型 '单击“清空接收缓冲区”按钮时,将接收缓冲区清空,此过程为“清空接收缓冲区”的单击事件 Private S ...

  2. 《Two Days DIV + CSS》读书笔记——CSS控制页面方式

    1.1 你必须知道的知识 (其中包括1.1.1 DIV + CSS的叫法解释:1.1.2 DIV + CSS 名字的误区:以及1.1.3 W3C简介.由于只是背景知识,跳过该章.) 1.2 你必须掌握 ...

  3. EffectiveC#16--垃圾最小化

    1.申请和释放一个基于堆内存的对象要花上更多的处理器时间. 所以当一个引用类型的局部变量在常规的函数调用中使用的非常频繁时应该把它提升为对象的成员(方法一) 2.当你把一个实现了IDisposable ...

  4. EffectiveC#11--选择foreach循环

    1.C#的foreach语句可以为你的任何集合产生最好的迭代代码 不推荐如下写法(?原因未明白 作者意思是阻碍jit边界检测) int len = foo.Length; for ( int inde ...

  5. a标签伪类的顺序

    在一次开发项目中,我用a链接来做效果,测试的时候发现,a:hover被点击后的效果就不再了!我百度才知道,原来在css写a链接也是有顺序之分的. 顺序应该是: a:link a标签还未被访问的状态: ...

  6. JS 事件对象和事件冒泡

    1.事件对象 js的事件对象中保存了当前被触发事件的一些相关的属性信息,如事件源.事件发生时的鼠标位置.事件按键等. 事件对象的获取方法: IE中可以window.event直接获取,而Firefox ...

  7. Android5.0+(CollapsingToolbarLayout)

    CollapsingToolbarLayout作用是提供了一个可以折叠的Toolbar,它继承至FrameLayout,给它设置layout_scrollFlags,它可以控制包含在Collapsin ...

  8. C学习笔记 - 指针

    指针与数组 ,,,,}; int *p; p = a; printf("*a = %d\n",*a); printf("*p = %d\n",*p); prin ...

  9. ORACLE SEQUENCE用法 (自增长)

    在oracle中sequence就是序号,每次取的时候它会自动增加.sequence与表没有关系. 1.Create Sequence     首先要有CREATE SEQUENCE或者CREATE ...

  10. C语言获取键盘按键

    在写控制台游戏的时候,发现不管用cin,scanf还是getchar,都不能实时的输入按键,必须要按回车才能读进去,而按回车的话会导致输入异常,所以要使用获取键盘按键的函数. 加入头文件#includ ...