Si
nh
Vi
en
Zo
ne
.C
om
Chương 2: Lập trình mạng trong windows
SinhVienZone.com
/>
Chương 2
1. Giới thiệu thư viện winsock
om
.C
ne
-
Zo
-
nh
Vi
en
-
Giao tiếp lập trình mạng cho phép phát triển ứng dụng giao tiếp trên cùng
một máy hoặc nhiều máy khác nhau thông qua môi trường mạng
Winsock được hỗ trợ sẵn trong windows cho phép lập trình mạng với giao
thức TCP/IP hoặc IPX
Lập trình Winsock trong windows ta sử dụng thư viện WINSOCK2.H,
WS2_32.LIB
Phiên bản winsock hỗ trợ cho các hệ điều hành Windows như sau:
Si
-
SinhVienZone.com
/>
Chương 2
1. Giới thiệu thư viện winsock
ne
nh
Vi
en
Zo
int WSAStartup(
WORD wVersionRequested,
LPWSADATA lpWSAData
);
.C
om
Khởi động Winsock
Trước khi chạy ứng dụng winsock cần khởi động thư viện winsock, winsock
DLL bằng hàm WSAStartup
Si
wVersionRequested : version của winsock
lpWSAData : trỏ tới struct LPWSADATA
SinhVienZone.com
/>
Chương 2
1. Giới thiệu thư viện winsock
Si
nh
Vi
en
Zo
ne
.C
om
Khởi động Winsock
typedef struct WSAData
{
WORD wVersion;
WORD wHighVersion;
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char FAR * lpVendorInfo;
} WSADATA, * LPWSADATA;
SinhVienZone.com
/>
Chương 2
1. Giới thiệu thư viện winsock
Si
nh
Vi
en
Zo
ne
.C
om
Kết thúc Winsock
Gọi hàm int WSACleanup(void);
SinhVienZone.com
/>
Chương 2
2. Tạo socket trong windows
Zo
ne
.C
om
Cú pháp
SOCKET socket (
int af,
int type,
int protocol
);
nh
Vi
en
af: họ địa chỉ giao thức, thiết lập là AF_INET nếu ta sử dụng IPv4
type: kiểu giao thức của socket, thiết lập là SOCK_STREAM cho TCP/IP,
SOCK_DGRAM cho UDP/IP
Protocol: thiết lập là IPPROTO_TCP đối với TCP, IPPROTO_UDP đối với
UDP
Si
-
SinhVienZone.com
/>
Chương 2
2. Tạo socket trong windows
Địa chỉ
om
-
ne
SOCKADDR_IN structure có dạng sau
struct sockaddr_in
nh
Vi
en
u_short sin_port;
Zo
{
short sin_family;
.C
winsock quản lý địa chỉ thông qua SOCKADDR_IN structure
struct in_addr sin_addr;
Si
char sin_zero[8];
};
sin_family : AF_INET
sin_addr : lưu trữ địa chỉ IP
sin_port : port
sin_zero : make the SOCKADDR_IN structure the same size as the SOCKADDR structure.
SinhVienZone.com
/>
Chương 2
client
socket
bind
Address
resolution
connect
Si
listen
nh
Vi
en
Zo
ne
socket
.C
Server
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
accept
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
.C
3.1 Server
ne
binding:
Zo
int bind(
nh
Vi
en
SOCKET s,
const struct sockaddr FAR* name,
int namelen
);
s: socket
Si
Khi socket được tạo ra cần dùng hàm bind để bind tới địa chỉ
name: kiểu địa chỉ socket struct sockaddr
namelen: kích thước của name
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
nh
Vi
en
int port = 5150;
Zo
SOCKADDR_IN tcpaddr;
ne
SOCKET s;
.C
Đoạn lệnh tạo socket và bind
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
tcpaddr.sin_family = AF_INET;
Si
tcpaddr.sin_port = htons(port);
tcpaddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(s, (SOCKADDR *)&tcpaddr, sizeof(tcpaddr));
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
.C
Listenning: lắng nghe kết nối từ client
ne
int listen(
Zo
SOCKET s,
nh
Vi
en
int backlog
);
Si
backlog : chiều dài tối đa của hàng đợi kết nối
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
SOCKET s,
nh
Vi
en
struct sockaddr FAR* addr,
Zo
ne
SOCKET accept(
.C
accepting: chấp nhận kết nối
int FAR* addrlen
);
Si
addrlen: tham chiếu tới kích thước của SOCKADDR_IN structure
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
.C
Chương trình phía server:
#pragma comment(lib, "wsock32.lib")
Zo
void main(void)
ne
#include <winsock2.h>
nh
Vi
en
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
Si
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int Port = 5150;
// Initialize Winsock version 2.2
WSAStartup(MAKEWORD(2,2), &wsaData);
SinhVienZone.com
/>
Chương 2
Chương trình phía server:
.C
// Create a new socket to listen for client connections.
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
ne
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ServerAddr.sin_family = AF_INET;
nh
Vi
en
ServerAddr.sin_port = htons(Port);
Zo
// Set up a SOCKADDR_IN structure that will tell bind that we
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Associate the address information with the socket using bind.
bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr));
Si
// Accept a new connection when one arrives.
NewConnection = accept(ListeningSocket, (SOCKADDR *)
&ClientAddr,&ClientAddrLen));
// At this point you can do two things with these sockets. Wait
// for more connections by calling accept again on ListeningSocket
// and start sending or receiving data on NewConnection
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
Chương trình phía server:
.C
closesocket(NewConnection);
ne
closesocket(ListeningSocket);
Zo
// When your application is finished handling the connections,
// call WSACleanup.
Si
nh
Vi
en
WSACleanup();
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
3.2 Client
Zo
void main(void)
ne
#pragma comment(lib, "wsock32.lib")
.C
#include <winsock2.h>
nh
Vi
en
{
WSADATA wsaData;
SOCKET s;
SOCKADDR_IN ServerAddr;
Si
int Port = 5150;
// Initialize Winsock version 2.2
WSAStartup(MAKEWORD(2,2), &wsaData);
// Create a new socket to make a client connection.
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
3.2 Client
.C
#include <winsock2.h>
{
SOCKET s;
nh
Vi
en
WSADATA wsaData;
Zo
void main(void)
ne
#pragma comment(lib, "wsock32.lib")
SOCKADDR_IN ServerAddr;
Si
int Port = 5150;
// Initialize Winsock version 2.2
WSAStartup(MAKEWORD(2,2), &wsaData);
// Create a new socket to make a client connection.
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SinhVienZone.com
/>
Chương 2
om
3. Xây dựng chương trình giao tiếp có kết nối
dùng winsock
3.2 Client
.C
// server IP: 136.149.3.29
Zo
ServerAddr.sin_port = htons(Port);
ne
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = inet_addr("136.149.3.29");
nh
Vi
en
// Make a connection to the server with socket s.
connect(s, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr));
// At this point you can start sending or receiving data on
closesocket(s);
Si
// the socket s. We will describe sending and receiving data
// When your application is finished handling the connection, call
// WSACleanup.
WSACleanup(); }
SinhVienZone.com
/>
Chương 2
4. Truyền/nhận dữ liệu
om
Hàm send và WSASend (dùng cho socket version 2)
Hàm send:
.C
int send(
nh
Vi
en
int len,
Zo
const char FAR * buf,
ne
SOCKET s,
int flags
);
buf : bộ đệm truyền dữ liệu
Si
flags: trạng thái send MSG_DONTROUTE, or MSG_OOB
SinhVienZone.com
/>
Chương 2
4. Truyền/nhận dữ liệu
Hàm WSASend :
om
int WSASend(
.C
SOCKET s,
ne
LPWSABUF lpBuffers,
Zo
DWORD dwBufferCount,
LPDWORD lpNumberOfBytesSent,
nh
Vi
en
DWORD dwFlags,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
Si
);
lpBuffers : buffer kiếu LPWSABUF
dwBufferCount : số lượng buffer
lpNumberOfBytesSent : số lượng bytes đã truyền
dwFlags: số bản sao
lpOverlapped and lpCompletionRoutine : thông số về đường truyền I/O
SinhVienZone.com
/>
Chương 2
4. Truyền/nhận dữ liệu
Ví dụ hàm send:
om
char sendbuff[2048];
// Fill sendbuff with 2048 bytes of data
ne
// Assume s is a valid, connected stream socket
.C
int nBytes = 2048, nLeft, idx;
Zo
nLeft = nBytes;
nh
Vi
en
idx = 0;
while (nLeft > 0)
{
ret = send(s, &sendbuff[idx], nLeft, 0);
{ // Error }
Si
if (ret == SOCKET_ERROR)
nLeft -= ret;
idx += ret;
}
SinhVienZone.com
/>
Chương 2
4. Truyền/nhận dữ liệu
om
Hàm recv and WSARecv
int recv(
.C
SOCKET s,
ne
char FAR* buf,
Zo
int len,
nh
Vi
en
int flags
);
Si
flags: có giá trị 0, MSG_PEEK, or MSG_OOB
SinhVienZone.com
/>
Chương 2
4. Truyền/nhận dữ liệu
om
Hàm WSARecv
int WSARecv(
.C
SOCKET s,
Zo
DWORD dwBufferCount,
ne
LPWSABUF lpBuffers,
nh
Vi
en
LPDWORD lpNumberOfBytesRecvd,
LPDWORD lpFlags,
);
Si
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
SinhVienZone.com
/>
Chương 2
client
socket
Zo
ne
socket
.C
Server
om
5. Xây dựng chương trình giao tiếp không kết
nối dùng winsock
nh
Vi
en
bind
sendto
Si
recvfrom
Address
resolution
SinhVienZone.com
/>
Chương 2
om
5. Xây dựng chương trình giao tiếp không kết nối
dùng winsock
Hàm recvfrom
.C
int recvfrom(
ne
SOCKET s,
Zo
char FAR* buf,
nh
Vi
en
int len,
int flags,
struct sockaddr FAR* from,
);
Si
int FAR* fromlen
flags : MSG_OOB or MSG_PEEK
SinhVienZone.com
/>