sockaddr_in
,位于netinet/in.h
头文件中,定义如下。
struct in_addr{
in_addr_t s_addr;
};
struct sockaddr_in{
uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero(0);
};
in_addr_t
in_port_t
位于netinet/in.h
in_addr_t
一般定义为uint32_t
,in_port_t
一般定义为uint16_t
sa_family_t
位于sys/socket.h
uint8_t
等位于sys/types.h
中sin_addr
sin_port
即为以网络字节序存储的32位ip地址与端口号sockaddr
,一般进行强制类型转换即可。sys/socket.h
中
int socket(int family, int type, int protocal);
AF_INET``AF_INET6
,分别表示IPv4/6协议。SOCK_STREAM
SOCK_DGRAM
SOCK_RAW
,分别表示字节流(TCP),数据报(UDP),原始套接字。IPPROTO_TCP‘
IPPROTO_UDP`通常设置为0也可。int connect(int sockfd, const struct sockaddr *servaddr, int addrlen);
int bind(int sockfd, const struct sockadddr *myaddr, int addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *cliaddr, int *addrlen)
int close(int sockfd);
int recv(int sockfd, void *buf, size_t len, int flags);
int send(int sockfd, const void *buf, size_t len, int flags);
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
int main(){
struct sockaddr_in local;
int s;
int sl;
int rc;
char buf[1000];
local.sin_family = AF_INET;
local.sin_port = htons(7500);
local.sin_addr.s_addr = htonl(INADDR_ANY);
s = socket(AF_INET, SOCK_STREAM, 0);
if ( s < 0){
perror("socket call failed");
exit(1);
}
rc = bind(s, (struct sockaddr *) &local, sizeof(local));
if ( rc < 0){
perror("bind call failed");
exit(1);
}
rc = listen(s, 5);
if ( rc < 0){
perror("listen call failed");
exit(1);
}
sl = accept(s, NULL, NULL);
if ( sl < 0){
perror("accept call failed");
exit(1);
}
rc = recv(sl, buf, 10, 0);
if ( rc < 0){
perror("recv call failed");
exit(1);
}
printf("%s\n", buf);
rc = send(sl, "good", 10, 0);
if ( rc < 0){
perror("send call failed");
exit(1);
}
exit(0);
}
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
int main(){
struct sockaddr_in peer;
int s;
int rc;
char buf[100];
peer.sin_family = AF_INET;
peer.sin_port = htons(7500);
peer.sin_addr.s_addr = inet_addr("127.0.0.1");
s = socket(AF_INET, SOCK_STREAM, 0);
if ( s < 0 ){
perror("socket call failed");
exit(1);
}
rc = connect(s, (struct sockaddr *) &peer, sizeof(peer));
if (rc){
perror("connect call failed");
exit(1);
}
rc = send(s, "hello", 10, 0);
if (rc <= 0)
{
perror("send call failed");
exit(1);
}
rc = recv(s, buf, 10, 0);
if (rc <= 0){
perror("recv call failed");
}
else
printf("%s\n", buf);
exit(0);
}
socket套接字TCP API,布布扣,bubuko.com
原文:http://blog.csdn.net/caozhk/article/details/38330997