时间:2021-05-20
c语言网络编程-标准步骤,真的很简单啊
server.c
复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 4444
#define BACKLOG 5
int main(int argc, char *argv[]) {
int sock_fd, new_fd;
struct sockaddr_in server_addr, client_addr;
int sin_size;
int nbytes;
int on = 1;
char buffer[1024];
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if (bind(sock_fd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(sock_fd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
printf("Server start... \n");
while (1) {
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sock_fd, (struct sockaddr *)(&client_addr), &sin_size)) == -1) {
perror("accept");
exit(1);
}
printf("Server get connection from %s\n", inet_ntoa(client_addr.sin_addr));
if ((nbytes = read(new_fd, buffer, 1024)) == -1) {
perror("read");
exit(1);
}
buffer[nbytes] = '\0';
printf("Server received: %s\n", buffer);
close(new_fd);
}
return 0;
}
client.c
复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 4444
int main(int argc, char *argv[]) {
int sock_fd;
struct sockaddr_in server_addr;
struct hostent *host;
char buffer[1024];
if (argc < 2) {
perror("Need hostname");
exit(1);
}
if ((host = gethostbyname(argv[1])) == NULL) {
perror("gethostbyname");
exit(1);
}
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
if (connect(sock_fd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) {
perror("connect");
exit(1);
}
printf("Please input something:\n");
fgets(buffer, 1024, stdin);
write(sock_fd, buffer, strlen(buffer));
close(sock_fd);
return 0;
}
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
使用C++实现对单张图片的读取和保存,C语言可以参考,比较简单。#includeusingnamespacestd;voidmain(void){//保存输入图
易语言作为国人开发的一门中文编程语言,深得不少人喜爱。他是一门中文的可视化编程语言,对于很多文化程度较低的人来说,编程也成为可能。虽然易语言比较简单,但还是有些
详解C语言用malloc函数申请二维动态数组的实例C语言在程序运行中动态的申请及释放内存十分方便,一维数组的申请及释放比较简单。Sampleone#includ
程序比较简单,用到了C语言获得自身路径和系统路径,修改注册表项等,某些函数不理解可以查看MSDN#include#includechar*GetFilename
本文实例为大家分享了C语言用电话簿管理系统的具体代码,供大家参考,具体内容如下c语言上机课程纠结了很久用函数还是链表,顺序表感觉函数比较简单实现:最后显示对齐还