recvfrom - How to convert buffer to string
I'm currently learning the network programming with C/C++... I have experience .NET but not in C (esp: in Unix network programming)
The problem that I'm facing right now is that when I receive the message, I like to split it into two parts. The format of message will be like [开发者_运维技巧command] filepath (For example: get a.txt or put a.txt)
I'm using recvform to receive the message.
int recvfrom(int sockfd, void *buf, int len, unsigned int flags,
struct sockaddr *from, int *fromlen);
The problem is that I dont know how to convert "void *buff" into string so that I can do String.Split(" ") to get the command and file name.
Could anyone please explain me a way to convert "void *buff" to string?
You actually pass the pointer to the start of a character array as the buffer. The recvfrom() system call writes into that array. You then process the array as a character string - after ensuring that it is properly null terminated (which recvfrom() will not do). Of course, the sending end has to put the data on in a compatible format, but the recvfrom() will give you what the sender sent you.
So, the direct answer is "You don't convert the void * into a character string; you convert the character string into a void * by passing it to recvfrom()".
You will want a character buffer and the size of the buffer. Like this:
char buf[1024];
const size_t buf_len = sizeof(buf);
Then you can call recvfrom like so:
ssize_t r;
r = recvfrom(sock, buf, buf_len-1, flags, &sock_from, &sock_from_len);
if(r<0) {
handle_error(r);
} else if(r == 0) {
handle_closed_socket(sock);
} else {
buf[r] = '\0';
}
The buf[r] = '\0'; will guarantee that your buffer is a proper null-terminated C string. Then you can pass buf around as a string.
C is not C++. There's no string class. The strtok function might help you get what you want, assuming you null terminate your buffer manually.
加载中,请稍侯......
精彩评论