#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<memory.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<netinet/in.h>
#define PORT 1234
int main()
{
struct sockaddr_in local_sockaddr;
int socketfd;//本地socket套接字描述符
if((socketfd=socket(AF_INET,SOCK_STREAM,0))<0)//建立socket连接
{
perror("socket");
exit(1);
}
printf("Socket id = %d\n",socketfd);
local_sockaddr.sin_family = AF_INET;
local_sockaddr.sin_port = htons(PORT);
local_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(local_sockaddr.sin_zero,0,8);
int i;
setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(i));//允许重复使用本地的地址与套接字进行绑定
if(bind(socketfd,(struct sockaddr *)&local_sockaddr,sizeof(struct sockaddr))<0)//绑定函数bind()
{
perror("bind");
exit(1);
}
printf("Bind success!\n");
close(socketfd);//关闭socket连接
}
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<memory.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<netinet/in.h>
#define PORT 1234
int main()
{
struct sockaddr_in local_sockaddr;
int socketfd;//本地socket套接字描述符
if((socketfd=socket(AF_INET,SOCK_STREAM,0))<0)//建立socket连接
{
perror("socket");
exit(1);
}
printf("Socket id = %d\n",socketfd);
local_sockaddr.sin_family = AF_INET;
local_sockaddr.sin_port = htons(PORT);
local_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(local_sockaddr.sin_zero,0,8);
int i;
setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(i));//允许重复使用本地的地址与套接字进行绑定
if(bind(socketfd,(struct sockaddr *)&local_sockaddr,sizeof(struct sockaddr))<0)//绑定函数bind()
{
perror("bind");
exit(1);
}
printf("Bind success!\n");
close(socketfd);//关闭socket连接
}