编写C语言客户端自定义带宽的例子.
时间: 2024-05-04 12:15:29 浏览: 83
C语言编写四则运算.doc
非常感谢您的问题。下面是一个简单的C语言客户端自定义带宽的例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <time.h>
#define PORT 8080
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in serveraddr;
struct hostent *server;
char buffer[256];
if (argc < 2) {
printf("Usage: %s hostname\n", argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(1);
}
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr,
server->h_length);
serveraddr.sin_port = htons(PORT);
if (connect(sockfd,(struct sockaddr *) &serveraddr,sizeof(serveraddr)) < 0) {
perror("ERROR connecting");
exit(1);
}
printf("Please enter the input string: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
clock_t start = clock();
int n = write(sockfd, buffer, strlen(buffer));
clock_t end = clock();
double elapsed_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Sent %d bytes in %f seconds\n", n, elapsed_time);
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) {
perror("ERROR reading from socket");
exit(1);
}
printf("%s\n",buffer);
close(sockfd);
return 0;
}
```
这个例子使用了C语言的socket库来发送字符串,同时记录了发送的时间和发送的字节数。如果您有任何问题,请随时问我哦。
阅读全文