rust


Convert String to SocketAddr


In versions of Rust before 1.0, I was able to use from_str() to convert a String to SocketAddr, but that function no longer exists. How can I do this in Rust 1.0.?
let server_details = reader.read_line().ok().expect("Something went wrong").as_slice().trim();
let server: SocketAddr = from_str(server_details);
let mut s = BufferedStream::new((TcpStream::connect(server).unwrap()));
from_str was renamed to parse and is now a method you can call on strings:
use std::net::SocketAddr;
fn main() {
let server_details = "127.0.0.1:80";
let server: SocketAddr = server_details.parse()
.expect("Unable to parse socket address");
println!("{:?}", server);
}
If you'd like to be able to resolve DNS entries to IPv{4,6} addresses, you may want to use ToSocketAddrs:
use std::net::{TcpStream,ToSocketAddrs};
fn main() {
let server_details = "stackoverflow.com:80";
let server: Vec<_> = server_details.to_socket_addrs()
.expect("Unable to resolve domain")
.collect();
println!("{:?}", server);
// Even easier, if you want to connect right away:
TcpStream::connect(server_details)
.expect("Unable to connect to server");
}
to_socket_addrs returns an iterator as a single DNS entry can expand to multiple IP addresses! Note that this code won't work in the Playground as network access is disabled there; you'll need to try it out locally.
I'll expand on "if you want to connect right away" comment in Shepmaster's answer.
Note that you don't really need to convert a string to a SocketAddr in advance in order to connect to something. TcpStream::connect() and other functions which take addresses are defined to accept an instance of ToSocketAddr trait:
fn connect<T: ToSocketAddr>(addr: T) -> TcpStream { ... }
It means that you can just pass a string to connect() without any conversions:
TcpStream::connect("stackoverflow.com:80")
Moreover, it is better not to convert the string to the SocketAddr in advance because domain names can resolve to multiple addresses, and TcpStream has special logic to handle this.

Related Links

compilation of openssl-sys fails with `openssl/hmac.h: No such file or directory`
Indexing a String
Importing mio::tcp::TcpStream but get std::net::tcp::TcpStream
It is possible to always have Cargo show warnings?
Copy files to the target directory after build
Is it ok to return in main?
Why is this trait/implementation incompatible - bound lifetime vs concrete lifetime
Cannot move out of `req` because it is borrowed
remove duplicates from vector of custom struct
error with % operator inside closure
How can I open a file with the standard text editor?
How to use multiple variables in routes with Nickel?
sdl2-sys won't compile - could not exec the linker: No such file or directory
Cannot borrow as mutable more than once at a time in one code - but can in another very similar
Forcing a move for an implemented `Copy` type
When do I need to specify explicit lifetimes in Rust?

Categories

HOME
jboss
weblogic12c
verification
vagrant
softlayer
histogram
celery
impala
onvif
hspi
yahoo
getopenfilename
nsstring
fullcalendar-scheduler
multi-step
deepfreeze
parceler
websphere-portal
chronicle-queue
quartz.net
mod-wsgi
tortoisemerge
webviewclient
hdmi
sap-lumira
sendmessage
private-key
overwrite
quickcheck
markov-chains
java-stream
redgate
installanywhere
recovery
rdp
right-click
coverage.py
optionaldataexception
jqgrid-asp.net
virtual-memory
zend-form
aws-kinesis-firehose
tinyioc
rm
nonlinear-functions
word-2007
deedle
google-shopping-api
scheduledexecutorservice
metabase
tsqlt
gcloud-node
ftp-client
raw-sockets
deferred-rendering
android-syncadapter
sharepoint-apps
accessibilityservice
chicagoboss
nastran
bjam
knife
relational-model
componentart
deque
fuseesb
dos2unix
datagridcomboboxcolumn
image-rotation
smacss
libgcc
rpg
mfmessagecomposeview
csslint
prism.js
meteor-collections
cloo
infinite
rautomation
codahale-metrics
apportable
mongo-jackson-mapper
cyrillic
semantic-merge
stretch
viewpagerindicator
image-scanner
monocross
azure-acs
kernel32
mongrel2
turbine
resharper-5.0
twitter-feed
comment-conventions
html-generation
rootkit

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App