/*
** talker.c -- a datagram "client" demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std ;
#define SERVERPORT "3200775" // the port users will be connecting to
int main()
{ string s;
ifstream f1 ("queries1.txt");
if (f1.is_open())
{
while (!f1.eof())
{
getline(f1,s);
cout<<s<<endl;
}
}
int sockfd;
//char ch [] = "hello";
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
// if (argc != 3) {
// fprintf(stderr,"usage: talker hostname message\n");
// exit(1);
//}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("nunki.usc.edu", SERVERPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("talker: socket");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
//if ((numbytes = sendto(sockfd,ch, strlen(ch), 0,
// p->ai_addr, p->ai_addrlen)) == -1) {
//perror("talker: sendto");
//exit(1);
//for (f=0 ;f<15; f++)
// {
char* mess = malloc(20*sizeof(char));
sprintf(mess,s);
if ((numbytes = sendto(sockfd,mess, s.length(), 0, p->ai_addr, p->ai_addrlen)) == -1)
{ cout<<s;
perror("talker: sendto");
exit(1);
}
printf("talker: sent %d bytes to \n", numbytes);
cout<<endl;
//}
freeaddrinfo(servinfo);
//printf("talker: sent %d bytes to \n", numbytes);
close(sockfd);
return 0;
}
对不起,马虎的编码方式。我在这里得到错误。我如何调试它?Sendto()函数给出错误。如何调试它们?
的错误是这些
test.cpp:84: error: invalid conversion from ‘void*’ to ‘char*’
test.cpp:85: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘2’ to ‘int sprintf(char*, const char*, ...)’
哇。那个缩进(或者它是否忽略它?)确实伤害了眼睛。 – sbi 2010-11-22 11:26:26
除非您告诉我们确切的错误,否则我们可以帮助您。 – thkala 2010-11-22 11:32:14
学会正确地缩进代码。很多问题都会得到解决。我在缩进代码的同时添加了一个右大括号。 – Aamir 2010-11-22 11:40:13